在您的模型中,您将设置此关联
class Article< ActiveRecord::Base
has_many :comments
end
class Comment< ActiveRecord::Base
belongs_to :article
end
所以每条评论都与一篇文章相关联,您需要一些逻辑来为评论找到对应的文章
这是嵌套路由的用武之地,可让您在控制器操作中找到该评论的文章。如果你再看看那条路线
/articles/:article_id/comments/:id(.:format)
这是评论控制器的显示动作,这条路线允许您在显示动作中找到文章和评论
def show
@article = Article.find(params[:article_id])
@comment = Comment.find(params[:id])
# if you are not using nested routes then you can find out associated article by
@article = @comment.article # but you'll have to query your database to get it which you can simply find if you are using nested route
end
不仅仅是显示操作(您可以在其中使用一些其他逻辑来查找与该评论关联的文章)您需要嵌套路由来执行新操作,您必须在其中找到该文章然后构建评论对于那篇文章,类似
def new
@article = Article.new
@comment = @article.comments.build
end
正如@August 指出的那样,您可以使用浅嵌套来分离出您希望路由嵌套的操作,您可以这样做:
resources :articles do
resources :comments, shallow: true
end
结帐nested routes了解更多信息