I know this is probably super simple, but for some reason I just can’t
get
it!
What I want to do is click on a post and display all the categories that
the
post is in.
class Post < ActiveRecord::Base
has_many :categories
end
class Category < ActiveRecord::Base
belongs_to :post
end
…simple enough.
In the categories_controller I have this:
def list_all_categories @post = Post.find(params[:id]) @categories = Category.find_all(params[:post])
end
In the list_all_categories view:
<% @categories.each do |cat| %>
<%= cat.name%>
<% end %>
The problem is that all the categories are showing up, instead of just
the
designated one(s). I tried using just the ‘find’ method, but that didn’t
work either. Any thoughts/ideas?
def list_all_categories @post = Post.find(params[:id]) @categories = Category.find_all(params[:post])
end
I think you are looking for:
@categories = @post.categories
I’ve been doing something similar and was wondering if creating a second
instance variable is considered better than just interating through the
items in the post.categories collection
ie
<% @post.categories.each do |cat| %>
<%= cat.name%>
<% end %>
Anyone any thoughts ?
-Tony
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.