Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/53.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 为多个资源添加公共路由_Ruby On Rails_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 为多个资源添加公共路由

Ruby on rails 为多个资源添加公共路由,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,如何一次性将/search端点添加到所有这些资源中 MyCoolApp::Application.routes.draw do resources :posts, only [:index, :show, :create] do collection { get :search } end resources :authors, only [:index, :show] do collection { get :search } end resource

如何一次性将
/search
端点添加到所有这些资源中

MyCoolApp::Application.routes.draw do

  resources :posts, only [:index, :show, :create] do
    collection { get :search }
  end

  resources :authors, only [:index, :show] do
    collection { get :search }
  end

  resources :comments, only: [:index, :show] do
    collection { get :search }
  end

  resources :categories, only: [:index, :show] do
    collection { get :search }
  end

  resources :tags, only: [:index] do
    collection { get :search }
  end
end
我看到了这一点,但我需要能够为reach资源指定操作。是否有更好的方法以更好的方式注入搜索路径

%w(one two three four etc).each do |r|
  resources r do
    collection do
      post 'common_action'
    end
  end
end
像这样的

resources :posts, only [:index, :show, :create, :search]

我知道您已经将这个问题标记为ruby-on-rails-3,但我将为将来遇到这个问题的任何人提供rails 4解决方案

Rails 4引入了

concern :searchable do
  collection do
    get :search
  end
end

resources :posts, only [:index, :show, :create], concerns: [:searchable]
resources :authors, only [:index, :show], concerns: [:searchable]
resources :comments, only: [:index, :show], concerns: [:searchable]
resources :categories, only: [:index, :show], concerns: [:searchable]
resources :tags, only: [:index], concerns: [:searchable]

啊,非常好。事实证明,我们实际上使用的是Rails 4,但我仍然习惯于使用与Rails 3相同的功能。让我测试一下,让你知道。效果很好!考试是绿色的:)谢谢!