Dolbery
Dolbery

Reputation: 185

How to simplify this Rails routing

So I want to manually route to a controller function, but do it identically for several resources

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) }

Is there a simpler way?

Upvotes: 1

Views: 57

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

Routing Concerns

You'll want to observe the resource-centric structure of Rails routing, coupled with the use of concerns. Specifically, how that will allow you to make your routes much DRY-er

You can achieve your result like this (simplistically):

#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

--

For the sake of keeping your code DRY, you'll likely want to use concerns as follows:

#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

Upvotes: 0

Santhosh
Santhosh

Reputation: 29124

Create a class like below in app/constraints

class SomeConstraint
  def matches?(request)
    # (something)
  end
end

And modify the routes

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

Upvotes: 1

Related Questions