user1670773
user1670773

Reputation:

Rails 4: has_many through associated object never return nil

I have two Model, Post and Category. They are connected by has_many through association. Categorization is the through table.

@post= Post.find(params[:Post_id])
@category = @post.categories

Some of my post are not under any category. It is possible to post without selecting any category. Problem is @category never show nil. I perform this check

<% if @category %>

    <% else %>

    <% end %>

This code never goes in else block even though there are no categories. Why is that? How can I check nil in this case?

Upvotes: 0

Views: 268

Answers (2)

bosskovic
bosskovic

Reputation: 2054

Chances are that since you have a potential for multiple categories, that you will want to do something with them, not just check if there are any.

In that case one thing you could do is render a partial for each category:

<%= render partial: my_category, collection: @category, as: :category %>

You should have a partial _my_category.html.erb:

<%= category %>

If there are no categories, no my_category partials will be rendered, so, no need for additional logic in the view.

Upvotes: 0

j-dexx
j-dexx

Reputation: 10416

@post.categories returns an activerecord relation,not nil. Because you're using rails I'd check it's presence using present?

<% if @vertiefungsrichtungs.present? %>
   # do something
<% else %>
   # do something else
<% end %>

Upvotes: 3

Related Questions