Reputation: 81
I have two tables
I have the following code in my controller:
@category = Category.find(id)
Suppose consider category as mobile, car, bike
I need to check the existence of mobile or car or bike. So that I can disable the input element. I tried:
<% @category.each do |cat| %>
<% if cat.posts.exists %>
class = 'active'
<% else %>
class = 'inactive'
<% end %>
<div class="#{class}"><%= cat.name %></div>
<% end %>
The above code always runs the else condition.
Following are the categories:
If in my post table with column category_id has the field with value 1
then mobile should have a class active
and the other two should be inactive.
Upvotes: 1
Views: 89
Reputation: 3368
I think you are looking for the any?
method:
<% @category.each do |cat| %>
<div class="#{cat.posts.any? ? 'active' : 'inactive'}"><%= cat.name %></div>
<% end %>
Upvotes: 2