【问题标题】:Changing the route behaviour but keeping the "Convention over Configuration"更改路由行为,但保持“约定优于配置”
【发布时间】:2011-09-24 19:35:22
【问题描述】:

我正在使用 Ruby on Rails 3.0.7,在我的应用程序中我有一个 Users::Article 类(注意它是命名空间的)。在routes.rb 文件中声明如下:

resources :users do
  resources :articles
end

我想设置与Users::Article 类相关的路由,以便我可以通过 URL /articles/articles/new/articles/1/articles/1/edit 访问它,但我仍想使用 RoR 约定优于配置“系统”。也就是说,我想使用:

  • Users::ArticlesHelper;
  • views/users/articles/<file_name>.html.erb查看文件;
  • 命名路线(<name>_path<name>_url);
  • 和其他“a la Ruby on Rails Way”...

我该怎么做?


简单地说,例如,我想引用/articles/1 路径,但要使应用程序完全按照users/<user_id>/articles/1 路径工作。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 configuration routing


    【解决方案1】:

    这不是美学问题,而是与路由参数有关。

    您可以使用/articles/:id,然后在控制器中引用所有者(用户)。

    在第二种情况下,/users/:user_id/articles/:id 会将 2 个参数传递给控制器​​。

    【讨论】:

      【解决方案2】:

      来自ActionDispatch::Routing::Mapper::Resources docs

      :shallow
      
      # Generates shallow routes for nested resource(s). When placed on a parent
      # resource, generates shallow routes for all nested resources.
      
      resources :posts, :shallow => true do
        resources :comments
      end
      
      # Is the same as:
      resources :posts do
        resources :comments, :except => [:show, :edit, :update, :destroy]
      end
      resources :comments, :only => [:show, :edit, :update, :destroy]
      
      # This allows URLs for resources that otherwise would be deeply nested such as a
      # comment on a blog post like /posts/a-long-permalink/comments/1234 to be
      # shortened to just /comments/1234.
      

      【讨论】:

        【解决方案3】:

        从 >rake routes

        得到这个
        users_articles      GET    /articles(.:format)           {:action=>"index", :controller=>"users/articles"}
                            POST   /articles(.:format)           {:action=>"create", :controller=>"users/articles"}
        new_users_article   GET    /articles/new(.:format)       {:action=>"new", :controller=>"users/articles"}
        edit_users_article  GET    /articles/:id/edit(.:format)  {:action=>"edit", :controller=>"users/articles"}
        users_article       GET    /articles/:id(.:format)       {:action=>"show", :controller=>"users/articles"}
                            PUT    /articles/:id(.:format)       {:action=>"update", :controller=>"users/articles"}
                            DELETE /articles/:id(.:format)       {:action=>"destroy", :controller=>"users/articles"}
        

        我们在 routes.rb 中需要这个

        namespace :users, :path => '' do
          resources :articles
        end
        

        注意:我使用的是 :namespace,正如你所说的那样。

        希望这会有所帮助。

        【讨论】:

          猜你喜欢
          • 2016-11-01
          • 2020-02-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-11-20
          • 2016-02-29
          相关资源
          最近更新 更多