Two actions for one route in Rails

2019-09-01 00:18发布

问题:

I have such problem:
I have two models: User and Page.
Users and Pages have field url.
So I have routes
get ':url' => 'users#show' and get ':url' => 'pages#show'
How should I redirect from this route to one of the actions users#show or pages#show?

回答1:

you will need a proxy action first, an action that checks if the url is a user or a page searching the db and then call the real action

something like

get 'users/:url', to: 'users#show', as: 'show_user'
get 'pages/:url', to: 'pages#show', as: 'show_page'
get ':url', to: 'application#user_or_page'

on ApplicationController

def user_or_page
  if u = User.find_by_permalink(params[:url])
    redirect_to show_user_path(u)
  elsif p = Page.find_by_permalink(params[:url])
    redirect_to show_page_path(p)
  else
    # do something with an invalid url
  end
end

I guess you can render some template instead of the redirects if you want that, but I would use a redirect



回答2:

There is a one to one relationship between a url and an action. So /url can either to to user#show OR pages#show, but not both.

Sounds like you may want two separate routes one for /users/url and /pages/url, in which case you may want routes like...

match 'users/url' => 'users#show'
match 'page/url' => 'pages#show'