【问题标题】:Is it possible to have same routes with different show action in rails?在rails中是否可以有不同的显示动作的相同路线?
【发布时间】:2014-06-12 07:18:18
【问题描述】:

我正在尝试在我的 rails 应用程序中访问以下网址:

example.com/user12 # It should show user#show
exmple.com/wordpress # It should show category#show

我的解决方案:(不起作用)

routes.rb 中,我已将:path => '' 添加到categories and users,以便从url 中删除控制器的名称。

resources :categories, :path => ''
resources :users, :path => ''

当我运行rake routes 时,我有以下网址”

category GET    /:id(.:format)   category#show
account GET    /:id(.:format)    accounts#show

所以我认为它应该可以正常工作,但肯定不是。它仅适用于类别名称和显示ActiveRecord::RecordNotFound 的用户名。

我知道,我的解决方案是错误的,因为我混淆了 Rails 路线系统,并且因为 resources :categoriesresources :users 具有更高的优先级,所以类别显示页面可以正常工作。

那么有什么办法可以解决这样的问题吗?

【问题讨论】:

  • 不,不同控制器直接处理相同的路由是不可能的,你需要将路由分开,例如“get '/category/:name' => 'category#show'” && “get '/account/:name' => 'account#show'"
  • 是的,如果我删除:path => '',路由将默认为控制器名称。
  • 是的,但它总是去第一个匹配的路线。并且默认情况下它与 Id 匹配,并且您正在尝试使用名称。这就是为什么它显示错误为“ActiveRecord::RecordNotFound”。

标签: ruby-on-rails ruby ruby-on-rails-4 routes


【解决方案1】:

我终于找到了constraints 选项的解决方案。此选项接受正则表达式。

resources :categories, :path => '', constraints: { id: /wordpress|php/ }

每个类别都应该以这种方式手动添加,或者(我不确定)也许有一种方法可以自动列出数据库中的所有类别。

【讨论】:

    【解决方案2】:

    这样做的一种方法是覆盖默认的 Rails 路由,删除resources

    我测试过,这行得通

    SampleRails4::Application.routes.draw do
      get '/user12', to: 'users#show' #=> users/show  
      get '/wordpress', to: 'category#show' #=> assuming u have a controller and action 
    end
    

    但是您必须更新其余代码,例如:users/show 可能期望用户 id 为 param read more 关于 Rails 路由

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-10
      • 2015-12-20
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 2014-06-17
      相关资源
      最近更新 更多