1

In view haml file I have a link, when you click, you get all the movies sorted by title or release date. The code in controller is:

def index
    sort = params[:sort] || session[:sort]
    case sort
    when 'title'
      ordering,@title_header = {:order => :title}, 'hilite'
    when 'release_date'
      ordering,@date_header = {:order => :release_date}, 'hilite'
    end
   # some more codes here
@movies = Movie.find_all_by_rating(@selected_ratings.keys, ordering)
end

if I change

ordering,@title_header = {:order => :title}, 'hilite'
to

 ordering,@title_header = {:order => title}, 'hilite'

It gives an error:

undefined local variable or method `title' for #<MoviesController:0xb29a853c>

3 Answers3

7
{:order => :title}

{:order => 'title'}

will both work. Take a look at this thread for differences between string and symbols : What's the difference between a string and a symbol in Ruby?

{:order => title}

Doesn't work because you're trying to assign to your hash key a value contained in the title local variable, and it doesn't exist, therefore it crashes

Community
  • 1
  • 1
Anthony Alberto
  • 10,325
  • 3
  • 34
  • 38
  • one more question, in View this is how I pass the "title" param. movies_path(:sort => 'title'), is that better to use movies_path(:sort => :title) ? – rubyknownothing Oct 31 '12 at 15:13
  • @user1727891 Yes, you should use the symbol here. Almost anytime you have a key that gets used repeatedly, symbols are more appropriate. – coreyward Oct 31 '12 at 15:26
  • although, when you deal with params in a controller (all keys are strings) it's useless to use symbol keys to get the values (they are converted into strings inside the hash) and you should NEVER NEVER OMG NEVER convert an arbitrary string to a symbol. Only use symbols you explicitly tyoe in the code. – rewritten Oct 31 '12 at 16:07
4

:title is a symbol. title is a local variable, or method.

You haven't defined title in this scope, hence your undefined local variable or method 'title' exception.

In other words, don't do that.

coreyward
  • 77,547
  • 20
  • 137
  • 166
1

You may want to use "title", a string...

ordering, @title_header = {:order => "title"}, 'hilite'
rewritten
  • 16,280
  • 2
  • 47
  • 50