我最初没有为正确的上下文发布足够的代码,但事实证明这是一个has_many :through, :source
习惯于(用 Rails 文档的话)“通过嵌套的 has_many 关联设置'快捷方式'”的示例。
class Post < ActiveRecord::Base
belongs_to :author, :class_name => "User"
has_many :comments, :foreign_key => :post_id
end
class Comment < ActiveRecord::Base
belongs_to :author, :class_name => "User"
belongs_to :post
belongs_to :parent, :class_name => "Comment", :foreign_key => "parent_comment_id"
has_many :replies, :class_name => "Comment", :foreign_key => "parent_comment_id"
end
class User < ActiveRecord::Base
has_many :posts, :foreign_key => :author_id
has_many :comments, :foreign_key => :author_id
has_many :post_feedback, :through => :posts, :source => :comments
end
:post_feedback
只是嵌套关联的自定义名称(:comments
已被使用)并且:source
使实际关联显式。现在 Rails 将理解User.post_feedback
并返回Comment
给定User
s上的所有Post
s,包括她自己的。