我刚开始学习Rails,刚接触过嵌套路由。我正在查看的示例涉及博客文章和评论。我想了解嵌套路由在 Rails 中的好处。
据我所知,评论的嵌套路由中包含的所有信息,例如 /articles/:article_id/comments/:id(.:format)
都包含在评论中对象本身,因此它不会向 Action 传递额外信息。
为什么不使用未嵌套的路由,例如 /comments/:id(.:format)
?
使用嵌套路由显然有很好的理由,但我一直无法解决。到目前为止,我能看到的唯一好处是它在阅读 URL 时更好地说明了文章和评论之间的关系,但所有这些信息无论如何都包含在评论对象中。
谁能解释一下?
最佳答案
在您的模型中,您将设置此关联
class Article< ActiveRecord::Base
has_many :comments
end
class Comment< ActiveRecord::Base
belongs_to :article
end
所以每个评论都与一篇文章相关联,您需要一些逻辑来为评论找到相应的文章
这就是嵌套路由的用武之地,让您可以在 Controller 操作中找到该评论的文章。如果你再看看那条路线
/articles/:article_id/comments/:id(.:format)
这是评论 Controller show action,这个路由允许你在 show action 中找到文章和你的评论
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
了解更多信息
关于ruby-on-rails - Rails 中的嵌套路由是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25219534/