[英]How to state a “direct” has_many association between two models through a third model?
I am using Ruby on Rails 4.1 and I would like to implement a "direct" has_many
association between Article
and CommentRequest
in the following case: 我正在使用Ruby on Rails 4.1,并且在以下情况下,我想在Article
和CommentRequest
之间实现一个“直接的” has_many
关联:
class Article < ActiveRecord::Base
has_many :comment_associations
has_many :comments, :through => :comment_associations
end
class Comment < ActiveRecord::Base
has_many :article_associations
has_many :articles, :through => :article_associations
has_many :comment_request_associations
has_many :comment_requests, :through => :comment_request_associations
end
class CommentRequest < ActiveRecord::Base
has_many :comment_associations
has_many :comments, :through => :comment_associations
end
That is, I would like to state a has_many
association in both Article
and CommentRequest
in order to make it possible to run code as-like the following: 也就是说,我想在Article
和CommentRequest
中都声明一个has_many
关联,以便可以像下面这样运行代码:
@article.comment_requests
@comment_request.articles
If it is possible, how to make that? 如果可能的话,如何做到这一点?
You should be able to do 你应该能够做
class Article < ActiveRecord::Base
has_many :comment_associations
has_many :comments, :through => :comment_associations
has_many :comment_requests, :through => :comments
end
since rails allows you to nest has_many :through
relationships 因为rails允许您嵌套has_many :through
关系
and similarly 同样
class CommentRequest < ActiveRecord::Base
has_many :comment_associations
has_many :comments, :through => :comment_associations
has_many :articles, :through => :comments
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.