开发者

Nested models with has_many in Rails

开发者 https://www.devze.com 2023-03-20 07:49 出处:网络
For example I have in my app model User, that has_many models Post. And Post has_many Attachment. So I can do this

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

精彩评论

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

关注公众号