如何简化此Rails路由

时间:2014-08-07 06:17:38

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

所以我想手动路由到控制器功能,但是对于几个资源来说是相同的

get "A/:id/f" => "a#f", :constraints=>lamba {|req| (something) }
get "B/:id/f" => "b#f", :constraints=>lamba {|req| (something) }
get "C/:id/f" => "c#f", :constraints=>lamba {|req| (something) }

有更简单的方法吗?

2 个答案:

答案 0 :(得分:1)

在app / constraints

中创建如下所示的类
class SomeConstraint
  def matches?(request)
    # (something)
  end
end

修改路线

constraints(SomeConstraint.new) do
  get "A/:id/f" => "a#f"
  get "B/:id/f" => "b#f"
  get "C/:id/f" => "c#f"
end

答案 1 :(得分:0)

Routing Concerns

您需要观察Rails routing的以资源为中心的结构,并结合使用concerns。具体来说,这将使您的路线更加干燥

你可以像这样(简单地)实现你的结果:

#config/routes.rb
resources :a do
   get :f, constraints: lamba {|req| (something) } #-> domain.com/a/:id/f
end

resources :b do
  get :f, constraints: lamba {|req| (something) } #-> domain.com/b/:id/f
end

resources :c do
  get :f, constraints: lamba {|req| (something) } #-> domain.com/c/:id/f
end

-

为了保持代码干,您可能希望使用如下问题:

#config/routes.rb
concern :your_items do
   get :f, constraints: lamba {|req| (something) } 
end

resources :a, :b, :c, concerns: :your_items #-> this might have to be split into separate "resources" declarations