Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - text_field class with condition

I want to give a text_field class on a condition. Is there a way to do it in rails?

I.e.

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

I need the class to be "required" only if a certain, condition occurs.

like image 898
Noam B. Avatar asked Dec 20 '22 05:12

Noam B.


2 Answers

Use ternary (condition ? then : else) operator:

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

It's not easy to read, but solves your problem. Alternatively you can set a variable to the requred class name before using it in the link:

<% class = 'required' if condition %>
<%= text_field 'person', 'employer', :tabindex => 5,:style => 'width: 50%;', 
               :class => class %>
like image 50
Matzi Avatar answered Dec 28 '22 23:12

Matzi


In general in rails you can do something like

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

Still your case is a bit more simple so you can do the check in place:

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

This will result in class being nil if condition is not met and 'required' otherwise.

like image 42
Ivaylo Strandjev Avatar answered Dec 28 '22 23:12

Ivaylo Strandjev