Listing/Relationship Question

Hello,

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?

Thank you,
Dave H.

Dave H. wrote:

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

Mat Cucuzella

Thank you Matt… that did the trick!

-Dave

mat wrote:

Dave H. wrote:

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