[Ruby] How to conditionally add html.erb class in Rails

less than 1 minute read


Suppose that you want to add a class to the class below only under “certain conditions”.

<div class="container">

For example, suppose this time you add a class only when it is users_controller. The conditional expression in that case is as follows.

<div class="container<%='user-container' if controller_name ='users' %>">

###※Note Be sure to leave a space before the first character of the class name you want to add.

Correct: <%='user-container' if...
Wrong: <%='user-container' if...

By adding class with such a condition, you can change or overwrite the style with CSS only under that condition, so please be sure to remember.