[英]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. 问题是如果值@ permission.role_id为nil,我只希望选择值为2。
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. 但这让Rails很生气。 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 好吧,我想我会在2分钟内感到愚蠢,但是怎么样呢
<%= 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: 你的解决方案不起作用的原因是你的
if
可以返回nil
,因此看起来像这样:
<%= f.collection_select :role_id, roles, :id, :name, :prompt => true, {nil} %>
Where {nil}
is syntax error 其中
{nil}
是语法错误
虽然三元运算符的公认解决方案有效,但我认为它不像以下解决方案那么可读:
<%= 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) %>
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. 我发现@ ecoologic的答案对我不起作用,因为ruby试图将哈希解释为最后一个参数的关键,而不是在哈希中查找值。
The solution was to use a ' splat '. 解决方案是使用' splat '。 However splats don't seem to work in that inline format, so I used the following:
但是splats似乎不能以内联格式工作,所以我使用了以下内容:
<% selected = @permission.role_id ? {} : {selected: 2 } %>
<%= f.collection_select :role_id, roles, :id, :name, prompt: true, **selected %>
The problem is that you can't have an if in that position. 问题是你不能拥有if在那个位置。 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 %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.