我想基于check_boxes创建一个表单,如果'@clans'数组不是nil并且它包含给定复选框的'value',我想要检查它。
我的第一个问题是:
<%= check_box_tag 'clans[]','Feniks', true if !@clans.nil? and @clans.include? 'Feniks' %>但是当@clans为nil时,check_box会消失,就像它被禁用一样。
我设法用这样的代码来解决它:
<% if !@clans.nil? and @clans.include? 'Feniks' %> Feniks: <%= check_box_tag 'clans[]','Feniks', true %> <% else %> Feniks: <%= check_box_tag 'clans[]','Feniks' %> <% end %>但它看起来很糟糕,必须有一个更好的方法来写这个:)
请告诉我如何处理这个:)
I want to make a form based on check_boxes, and I want it to be checked, if '@clans' array is not nil and it contains a 'value' of a given checkbox.
My first atemnpt was:
<%= check_box_tag 'clans[]','Feniks', true if !@clans.nil? and @clans.include? 'Feniks' %>but when @clans is nil, the check_box disappears, just like it was disabled.
I managed to solve it with code like that:
<% if !@clans.nil? and @clans.include? 'Feniks' %> Feniks: <%= check_box_tag 'clans[]','Feniks', true %> <% else %> Feniks: <%= check_box_tag 'clans[]','Feniks' %> <% end %>but it looks so bad, that there have to be a better way to write this :)
Please show me how to handle this :)
最满意答案
将if逻辑包含在括号内。
<%= check_box_tag 'clans[]','Feniks', (true if !@clans.nil? and @clans.include? 'Feniks') %>在您的代码中, if作为修饰符使用。 喜欢print 10 if x.present? 。 在此示例中,如果x不为空 ,则此方法将调用print(10) ,否则不会。 同样的类比也适用于您的情况。 在erb标记内,您的代码被解释为:
<%= check_box_tag('clans[]','Feniks', true) if <condition> %>这就是为什么当条件为真时, check_box_tag方法被调用,否则不被调用。 您可以将整个if部分写为:
<%= check_box_tag 'clans[]','Feniks', @clans.try(:include?, 'Feniks') %>Wrap the if logic inside parenthesis.
<%= check_box_tag 'clans[]','Feniks', (true if !@clans.nil? and @clans.include? 'Feniks') %>In your code, if working as a modifier. Like print 10 if x.present?. In this sample, if x is not blank, the this method call print(10) will be happened, otherwise not. Same analogy holds for your case also. Inside the erb tag, you code is being interpreted as :
<%= check_box_tag('clans[]','Feniks', true) if <condition> %>That's why when condition is true, check_box_tag method is getting invoked otherwise not. You could write the whole if part as :
<%= check_box_tag 'clans[]','Feniks', @clans.try(:include?, 'Feniks') %>更多推荐
发布评论