4

我想在一个条件下给出一个 text_field 类。有没有办法在rails中做到这一点?

IE

<%= text_field 'person', 'employer', :tabindex => 5,:style => 'width: 50%;', :class => 'required' %>

仅当发生某种情况时,我才需要“要求”该课程。

4

2 回答 2

8

使用三元 ( condition ? then : else) 运算符:

<%= text_field 'person', 'employer', :tabindex => 5,:style => 'width: 50%;', 
               :class => (condition ? 'required': '') %>

它不容易阅读,但可以解决您的问题。或者,您可以在链接中使用之前将变量设置为所需的类名:

<% class = 'required' if condition %>
<%= text_field 'person', 'employer', :tabindex => 5,:style => 'width: 50%;', 
               :class => class %>
于 2013-05-22T11:24:53.147 回答
4

一般来说,在rails中你可以做类似的事情

<% if condition %>
  <%= text_field 'person', 'employer', :tabindex => 5,:style => 'width: 50%;', :class => 'required' %>
<% else %>
  <%= text_field 'person', 'employer', :tabindex => 5,:style => 'width: 50%;' %>
<% end %>

您的情况仍然更简单,因此您可以就地进行检查:

  <%= text_field 'person', 'employer', :tabindex => 5,:style => 'width: 50%;', :class => condition ? 'required' : nil %>

如果不满足条件,这将导致类为零,否则为“必需”。

于 2013-05-22T11:27:34.830 回答