Prabhakaran8737
Prabhakaran8737

Reputation: 81

how to check whether association exists rails

I have two tables

  1. Post
  2. Category

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:

  1. Mobile
  2. Car
  3. Bike

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

Answers (1)

jvperrin
jvperrin

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

Related Questions