Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails - collection_select selected value if defined?

I have the following:

<%= f.collection_select :role_id, roles, :id, :name, :prompt => true, :selected => 2 %>

Problem is I only want the selected value of 2 if the value @permission.role_id is nil.

so I tried:

<%= f.collection_select :role_id, roles, :id, :name, :prompt => true, {:selected => 2 if @permission.role_id.nil?} %> 

but that made Rails angry. How can I make a condition selected value based on if a separate variable is nil or not?

Thanks

like image 544
AnApprentice Avatar asked Jan 15 '11 18:01

AnApprentice


3 Answers

ok I guess I'll feel stupid in 2 mins, but what about

<%= f.collection_select :role_id, roles, :id, :name, prompt: true, @permission.role_id ? {} : {selected: 2 } %>

The reason why your solution is not working is that your if can return nil, therefor looking something like that:

<%= f.collection_select :role_id, roles, :id, :name, :prompt => true, {nil} %>

Where {nil} is syntax error

like image 67
ecoologic Avatar answered Sep 16 '22 15:09

ecoologic


While the accepted solution with the ternary operator works, I don't think it is quite as readable as the following solution:

<%= f.collection_select :role_id, roles, :id, :name, :prompt => true, :selected => @permission.role_id || 2 %>
like image 24
saneshark Avatar answered Sep 20 '22 15:09

saneshark


put this in your helper

def selected(permission)
  if permission.role_id.nil?
    return 2
  else
    .....
  end
end

and this in your view

<%= f.collection_select :role_id, roles, :id, :name, :prompt => true, :selected => selected(@permission) %>
like image 41
Andrei S Avatar answered Sep 16 '22 15:09

Andrei S