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
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
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 %>
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) %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With