[英]Nested models with has_many in Rails
For example I have in my app model User, that has_many models Post.例如,我的应用程序中有 model 用户,即 has_many models Post。 And Post has_many Attachment.并发布 has_many 附件。 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?有没有内置的解决方案?
You would use a has_many through association.您将通过关联使用 has_many 。 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... has_many:through 关联对于通过嵌套的 has_many 关联设置“快捷方式”也很有用...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.