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
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) %>
The problem is that you can't have an if in that position. So a first solution, though a bit ugly, is something like the following:
<% if @permission.role_id.nil? %>
<%= f.collection_select :role_id, roles, :id, :name, :prompt => true, {:selected => 2} %>
<% else %>
<%= f.collection_select :role_id, roles, :id, :name, :prompt => true %>
<% end %>
I found @ecoologic's answer didn't work for me as ruby attempted to interpret the hash as a key for a last argument instead of looking inside the hash for values.
The solution was to use a 'splat'. However splats don't seem to work in that inline format, so I used the following:
<% selected = @permission.role_id ? {} : {selected: 2 } %>
<%= f.collection_select :role_id, roles, :id, :name, prompt: true, **selected %>
精彩评论