Elliot
Elliot

Reputation: 13835

If statement with form field select in rails

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?

Upvotes: 0

Views: 1824

Answers (1)

Matchu
Matchu

Reputation: 85794

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) %>

Upvotes: 2

Related Questions