Forum: Ruby on Rails Listing/Relationship Question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Dave H. (Guest)
on 2006-02-22 05:04
(Received via mailing list)
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.
mat (Guest)
on 2006-02-22 07:06
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
Dave H. (Guest)
on 2006-02-22 08:08
(Received via mailing list)
Thank you Matt... that did the trick!

-Dave
Anthony G. (Guest)
on 2006-02-22 13:59
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
This topic is locked and can not be replied to.