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.
12be02204a4bcaeec2c6c369fe53a45b?d=identicon&s=25 Dave Hoefler (Guest)
on 2006-02-22 04: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 Hoefler
8adbed24cb8d91bfb8dce6cf1e7141b6?d=identicon&s=25 mat (Guest)
on 2006-02-22 06:06
Dave Hoefler 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
12be02204a4bcaeec2c6c369fe53a45b?d=identicon&s=25 Dave Hoefler (Guest)
on 2006-02-22 07:08
(Received via mailing list)
Thank you Matt... that did the trick!

-Dave
F59329dc91cba06600ff65c85fd3e93c?d=identicon&s=25 Anthony Green (acgreen)
on 2006-02-22 12:59
mat wrote:
> Dave Hoefler 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.