Rails 嵌套路径,不是资源

Rails Nesting paths, not resources

我有一个 Author 模型,其中 name 作为字段 - 它 has_many 文章。

我还有一个 Article 模型,其中 namedescription 作为字段 - 它是 belongs_to 作者和 has_many 评论。

最后,我有一个 Comment 模型,其中 comment_textarticle_id 作为字段 - 它 belongs_to 文章,

我正在寻找嵌套路径 i。 e. ,(作者/:id/comments) 如何嵌套路径而不是资源?

澄清一下,我不想在 Comment 模型中使用 author_id,但是当我访问 authors/:id/comments 时,我应该能够看到与 author 和对他们发表评论。

作者

has_many :articles
has_many :comments, :through => :articles (This line will give you comments for the author)

文章

belongs_to :author (means it has author_id as a field)
has_many :comments

评论

belongs_to :article

如果你的模型中有上述结构,那么你可以这样做:

@author = Author.where(:id => some_id)
@comments = @author.comments

您不需要在评论 table.

中包含 author_id