开发者

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 t开发者_Python百科his

post.attachment

But what if I want do smth like

user.attachments

Is there any build-in solution for this?


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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜