Peter Tretiakov
Peter Tretiakov

Reputation: 3410

Routes get error

I have two get methods in routes.rb

get 'orders/:id-:phone', to: 'orders#show', as: :order_phone
get ':id/:url', to: 'point_pages#show', as: :page_url

So, for Order model I need to have URL like: domain.com/orders/1-88888888888 (88888888888 - is a phone number of order.user) and for PointPage model - domain.com/1/some_long_point_page_url.

But when I create new Order and rails redirect to order_phone_path(@order), I receive an error:

Couldn't find PointPage with id=orders

So, I need to tell rails, that when URL is domain.com/orders/..., it uses the first get method for Order, and when URL is domain.com/1-... (or other number) it uses the second get method for PointPage.

Thanks!

Upvotes: 0

Views: 44

Answers (2)

Richard Peck
Richard Peck

Reputation: 76784

You'll may want to do the following:

#config/routes.rb
resources :point_pages, only: [], path: "" do
   get :url, action: :show, as: :page_url # -> domain.com/:id/:url to show
end

resources :orders, only: [] do
   get ":id-:phone", action: :show, on: :collection, as: :order_phone # -> domain.com/orders/:id-:phone
end

This might look a little haphazard, but it's definitely the best way to keep your application's routes as convention would direct.

I know you have the answer, so hopefully this will give you some better understanding of how you may benefit from structuring the routes as above

Upvotes: 0

vee
vee

Reputation: 38645

If you really have to use a route as such then swap the position of get method calls as:

get ':id/:url', to: 'point_pages#show', as: :page_url
get 'orders/:id-:phone', to: 'orders#show', as: :order_phone

This way the first route catches your URI. Note that the order of routes defined is important. If two routes match a given pattern then the route defined earlier is used.

Note that with this definition:

get ':id/:url', to: 'point_pages#show', as: :page_url

all your routes would get caught by it. So, it's definitely advised to prepend path to the controller or some unique literal before any variables. E.g:

 get 'point_pages/:id/:url', to: 'point_pages#show', as: :page_url

Upvotes: 1

Related Questions