0

I got this code, and i get the "Missing method" when i try to use the second more elegant approach. I think the documentation at: http://guides.rubyonrails.org/active_record_querying.html is rather unhelpful or incomplete. Any ideas?

By the way, feel free to help write an even more "oneliner" elegant approach to this :)

  def index
@sortby = params[:sort_by]

# THIS WORKS

#if @sortby == nil
#  @movies = Movie.all
#else
#  @movies = Movie.order(@sortby)
#end

# THIS DOESNT. WHY? I THOUGHT METHOD CHAINING AND LAZYLOAD WOULD WORK.
@movies = Movie.all
@movies = @movies.order(@sortby) unless @sortby == nil

end

tereško
  • 58,060
  • 25
  • 98
  • 150
imbageek
  • 609
  • 5
  • 18
  • Your code is open to sql injection attack: http://stackoverflow.com/questions/7771103/rails-3-activerecord-order-what-is-the-proper-sql-injection-work-around – house9 Feb 10 '13 at 16:12

2 Answers2

0

all loads records and returns array. Try to use scoped:

@movies = Movie.scoped
@movies = @movies.order(@sortby) unless @sortby.nil?
Babur Ussenakunov
  • 1,995
  • 2
  • 16
  • 16
0

You can do this in one line.

@movies = params[:sort_by].nil? ? Movie.all : Movie.order(params[:sort_by]).all

In your case you are getting error about 'undefined method order for Array' I suppose. ActiveRecord method .all returns array.

jizak
  • 382
  • 2
  • 13