Conditionally add a class to link_to in Rails
You can do it outside the link_to
:
<% css_class = accepted ? "hidden" : "" %>
<%= link_to "Accept Friend Request",
"#",
class: "btn btn-success btn-sm btn-block requestSent #{css_class}",
disabled: true %>
I posted a similar answer to this question.
A cleaner solution
The standard approach requires putting logic into the views and using string interpolation or moving things into a separate helper.
Here's an updated approach that avoids any of that:
<%= link_to "Accept Friend Request",
"#",
class: class_string("btn btn-success btn-sm ban-block requestSent" => true, hidden: accepted),
disabled: true %>
class_string
method
The class_string
helper takes a hash with key/value pairs consisting of CSS class name strings and boolean values. The result of the method is a string of classes where the boolean value evaluated to true.
Sample Usage
class_names("foo bar" => true, baz: false, buzz: some_truthy_variable)
# => "foo bar baz"
Inspired by React
This technique is inspired by an add-on called classNames
(formerly known as classSet
) from Facebook’s React
front-end framework.
Using in your Rails projects
As of now, the class_names
function does not exist in Rails, but this article shows you how to add or implement it into your projects.
If you use interpolation with #{}, anything you put between it is run as plain old Ruby code. In this example you could add a conditional class in the string like this:
<%= link_to "Accept Friend Request",
"#",
class: "btn btn-success btn-sm btn-block requestSent #{'hidden' if accepted}",
disabled: true %>
Just note that you should use single quotes around the class name 'hidden'.
Also note that when a variable represents a boolean value (true or false), you don't need to explicitly say if accepted == true
. You can simply say if accepted
.
You can use a helper to build up the link as well:
def accept_friend_request_link
classes = [:btn, :and_friends]
if accepted
classes << :hidden
end
link_to 'Accept Friend Request', '#', class: classes, disabled: true
end