views:

37

answers:

1

I'm trying put an if statement directly into a select field in rails, with no success.

Here is what I've tried:

    <%= f.select (:book_id,{ 
    if @a!=1
            "Harry Potter", 1,
    end
    if @b!=2
            "Lord of the Rings", 2,
    end
    end %>`

Any ideas?

+1  A: 

Don't do this. It's ugly, and not fun for you to maintain. Also, no good trying to put if-statements or anything other than hash values inside a hash declaration. How about a helper?

Helper code (untested):

def book_select(f)
  options = {}
  options['Harry Potter'] = 1 unless @a == 1
  options['Lord of the Rings'] = 2 unless @b == 2
  f.select :book_id, options
end

View code:

<%= book_select(f) %>
Matchu
Hi Matchu,Thanks for the advice, I'm pretty new to rails - how/where would I implement that?
Elliot
The helper code goes in the helper for this controller - so if it's the books controller, the file probably already exists at `app/helpers/books_helper.rb`. Put in the function as a method of the helper class, and then it will be available to you in the view, as demonstrated in the second code block :)
Matchu
Awesome thanks!
Elliot