0

我对 Rails 还很陌生,我正在尝试更好地了解如何利用 Rails 框架进行关联。

虽然它不是特定于我的应用程序,但结构是相似的——在我的示例中,我将使用标准的 blog associates。

示例模型:

class Author < ActiveRecord::Base
    has_many :posts, :through => :posts
end

class Post < ActiveRecord::Base
    belongs_to :author
    has_many :comments
end

class Comment < ActiveRecord::Base
    belongs_to :post
end

我的挑战是我想选择属于特定作者的所有评论。我了解如何引用与特定帖子相关联的帖子和作者元素:

comment_author = Comment.first
puts comment_author.post.author.name

但正如我所说,我正在尝试选择属于特定作者的所有评论。我可以通过执行 find_by_sql 来完成此操作,但我想确保数据库独立性并且我想以“Rails 方式”来做到这一点。

谢谢!

4

2 回答 2

0

您可以使用has_many :through关联:

class Author < ActiveRecord::Base
    has_many :posts
    has_many :comments, :through => :posts
end
于 2012-04-07T14:04:58.740 回答
0

@Femaref 为您的问题提供了确切答案,您应该接受它。我的只是一个补充。


如果作者可以对帖子发表评论,您可能需要执行以下操作:

class Author
  has_many :posts
  has_many :comments
  has_many :responses, through: :posts, source: :comments                           
end

class Post
  belongs_to :author
  has_many :comments
end

class Comment
  belongs_to :author
  belongs_to :post
end

要获得所有留下的评论sophiasophia.comments

sophia要获得所有帖子留下的评论:sophia.responses

请参阅(尤其是和)的选项has_manythroughsource

于 2012-04-07T15:07:33.770 回答