Find all by a different association id

I have 3 models here setup like thus:

AttachmentType
has_many :attachments

Attachment
belongs_to :page
belongs_to :attachment_type

Page
has_many :attachments

Attachment belongs to both an AttachmentType & Page.

How can I find all AttachmentType by a page id?

I suppose I could say that AttachmentType has_one :page, but that
seems a bit unnecessary.

On 9 April 2010 19:25, Brent [email protected] wrote:

   has_many :attachments

How can I find all AttachmentType by a page id?

Page
has_many :attachments
has_many :attachment_types :through => :attachments

Hmm… OK I did this and I can grab attachment_types through a page.
BUT I can’t grab the specific attachments in the attachment_types in a
page… for instance if I try this:

@types = @page.attachment_types
<% @types.each do |t| %>
<%= render(:partial => ‘partial/attachment’, :collection =>
t.attachments) %>
<% end %>

It looks like when I grab attachments from the type, it grabs ALL
attachments from that type, not attachments specifically associated to
that page. How can I tell it to do a :through, with a model that isn’t
associated in the AttachmentType model?

OK I think I found the solution:

@types = @page.attachment_types

<% @types.each do |t| %>
<%= render(:partial => ‘partial/attachment’, :collection =>
t.attachments.find_all_by_page_id(@page.id)) %>
<% end %>

didn’t know I could still call the find_all_by_page_id after I called
it from a model.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs