Rails嵌套路径,而不是资源

时间:2015-07-11 04:54:33

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2

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

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

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

我正在寻找筑巢路径。即(作者/:ID /评论) 如何嵌套路径,而不是资源?

为了澄清,我不想在评论模型中使用author_id,但是当我访问作者/:id / comments时,我应该能够看到与作者相关的所有文章和评论它们。

1 个答案:

答案 0 :(得分:1)

<强>作者

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

您不需要在评论表中包含 author_id

相关问题