【问题标题】:What are nested routes for in Rails?Rails 中的嵌套路由是什么?
【发布时间】:2014-10-02 21:07:11
【问题描述】:

我是学习 Rails 的新手,刚刚遇到嵌套路由。我正在查看的示例涉及博客文章和 cmets。我试图理解嵌套路由在 Rails 中的好处。

据我所知,/articles/:article_id/comments/:id(.:format) 等评论的嵌套路由中包含的所有信息都包含在评论对象本身中,因此它不会向 Action 传达其他信息。

为什么不只使用诸如/comments/:id(.:format) 之类的非嵌套路由?

使用嵌套路由显然有很好的理由,但我无法解决。到目前为止,我能看到的唯一好处是它在阅读 URL 时更好地说明了文章和 cmets 之间的关系,但所有这些信息都包含在评论对象中。

有人能解释一下吗?

【问题讨论】:

    标签: ruby-on-rails routing routes nested-routes


    【解决方案1】:

    在您的模型中,您将设置此关联

    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了解更多信息

    【讨论】:

      【解决方案2】:

      正确,在处理预先存在的comment 时,在路径中包含article 是多余的(因为您可以从comment 获得article)。为避免这种情况,您可以使用shallow 路由:

      #routes.rb
      
      resources :articles, shallow: true do
        resources :comments
      end
      
      # or use a `shallow` block
      shallow do
        resources :articles
          resources :comments
        end
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-28
        相关资源
        最近更新 更多