Rails - 带条件的text_field类

Noa*_* B. 2 ruby-on-rails

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

<%= text_field 'person', 'employer', :tabindex => 5,:style => 'width: 50%;', :class => 'required' %>
Run Code Online (Sandbox Code Playgroud)

只有在某种情况发生时,我才需要"必需".

Mat*_*tzi 7

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

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

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

<% class = 'required' if condition %>
<%= text_field 'person', 'employer', :tabindex => 5,:style => 'width: 50%;', 
               :class => class %>
Run Code Online (Sandbox Code Playgroud)