Black Disc
Black Disc

Reputation: 5

I don't understand why this Ruby on Rails code for f.select with options_from_collection_for_select does not work

I am a newbie to Ruby (2.2.3) on Rails (4.2.4) and am trying some new code out. When I enter the Code below I get the following error.

Code:

     <%= f.select (:food_preference_id,
     options_from_collection_for_select(FoodPreference.all, :id, :name),
     {:prompt => 'Please Choose'}, {:class => "form-control"})  
     %>

Error:

      > syntax error, unexpected ',', expecting ')' 

The error refers to the comma after :food_preference_id.

But when I type in the code without the brackets (as follows) it works

<%= f.select :food_preference_id,
 options_from_collection_for_select(FoodPreference.all, :id, :name),
 {:prompt => 'Please Choose'}, 
 {:class => "form-control"}  
%>

I don't understand why the code works without the brackets and does not work with the brackets. Can someone help me understand. Thanks in advance.

Upvotes: 0

Views: 59

Answers (2)

jvillian
jvillian

Reputation: 20263

Great catch, Arup!

For the OP, the thing to understand is that .select is a method call on the form builder object (f) created by your form_for :object do |f| statement. (Or whatever variation you are using.)

When calling methods using parameters (or arguments, whichever you prefer) contained within parentheses, the initial parenthesis must immediately follow the method name. So, as Arup points out,

this.is(:okay)

but

this.is (:not_okay)

You are not required, however, to use parentheses. So,

this.is :also_okay

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118271

You can't have space between method name and bracket.

f.select (:food_preference_id
        ^^

Write the code

 <%= f.select(:food_preference_id,
     options_from_collection_for_select(FoodPreference.all, :id, :name),
     {:prompt => 'Please Choose'}, {:class => "form-control"})  
 %>

Upvotes: 4

Related Questions