rails check

编程入门 行业动态 更新时间:2024-10-21 06:37:27
rails check_box_tag disapear(rails check_box_tag disapear)

我想基于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') %>

更多推荐

本文发布于:2023-04-29 10:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1336363.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:rails   check

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!