Reputation:
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
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