Ximik
Ximik

Reputation: 2495

Nested models with has_many in Rails

For example I have in my app model User, that has_many models Post. And Post has_many Attachment. So I can do this

user.posts

and this

post.attachment

But what if I want do smth like

user.attachments

Is there any build-in solution for this?

Upvotes: 1

Views: 288

Answers (1)

Gazler
Gazler

Reputation: 84150

You would use a has_many through association. You should end up with something similar to the following structure:

class User < ActiveRecord::Base
  has_many :posts
  has_many :attachments, :through => :posts
end

class Post < ActiveRecord::Base
  has_many :attachments
end

class Attachments < ActiveRecord::Base
  belongs_to :posts
end

The relevant section from the above link:

The has_many :through association is also useful for setting up “shortcuts” through nested has_many associations...

Upvotes: 3

Related Questions