1

I am new to rails.In my rails application i want to sort content with respect to a dropdown list.

In my dropdown list i have several option like "name", "price". Now if i press name from the list i want the content to be sorted by name of the content.see the picture:when i select from the sort by dropdown then i want to sort the content according to selected option

I have no idea how to do this in rails .

Please help me out.

monsur
  • 601
  • 6
  • 18
  • 1
    check out [sort](http://ruby-doc.org/core-2.0.0/Enumerable.html#method-i-sort) and [sort_by](http://ruby-doc.org/core-2.0.0/Enumerable.html#method-i-sort_by) – dax Nov 10 '13 at 11:19

1 Answers1

2

We can't suggest You anything specific unless You share Your controller code. In most cases You just specify order clause to Your DB query.

For instance:

class ProductsController < ApplicationController
  def index
    # assuming You passed order field in GET param: /products?order_by=name
    @products = Product.order(params[:order_by])
  end
end

UPDATED

You should be able to use it this method for quoting. It's defined on Your connection object (SomeModel.connection)

irb(main):001:0> Movie.connection.quote_column_name("name")
=> "\"name\""
irb(main):004:0> Movie.connection.quote_column_name("name; DELETE FROM users;")
=> "\"name; DELETE FROM users;\""

Even better probably would be using only column names defined by You.

Edgars Jekabsons
  • 2,833
  • 15
  • 20
  • 1
    Beware, your example code is open to sql injection attacks, see http://stackoverflow.com/questions/7771103/rails-3-activerecord-order-what-is-the-proper-sql-injection-work-around - note rails will handle params passed to the where method, but not the order method – house9 Nov 10 '13 at 22:28
  • 1
    thanks for replying.My form code is : <%= form_for(@category, :url => sort_item_category_path, method: 'GET', :class=> " form-inline pull-left") do |f| %> Sort By : end .i wanna know how to send the params[:order_by] to controller @edgarsJejabsons – monsur Nov 11 '13 at 05:10
  • Agree it should be escaped. – Edgars Jekabsons Nov 11 '13 at 07:40
  • 1
    user1463066, add all code blocks to the question, Your comment is barely readable. – Edgars Jekabsons Nov 11 '13 at 07:52