Chris Yeung Chris Yeung - 7 months ago 26
Ruby Question

Conditionally add class to link_to with slim syntax

I have a link and the code is as follows:

= link_to 'Payment', account_payment_path, class:{'active'}


and I want to add a conditional logic to the view, so if the
action_name
is same, then add class
active


I then change to the following code

= link_to 'Payment', account_payment_path, class:{'active' if action_name == 'payment'}


but it results in error. How can I fix it.?

Answer

If you want to get active links there is a gem build for that active_link_to, you can use it like this and it will handle adding the active class for you:

=active_link_to 'Payment', account_payment_path

for your problem you can use this:

= link_to 'Payment', account_payment_path, class: (action_name == 'payment' ? 'active' : '')