Rails 中一条路线的两个动作 [英] Two actions for one route in Rails
问题描述
我有这样的问题:
我有两个模型:用户和页面.
用户和页面具有url字段.
所以我有路线get ':url' =>'users#show'
和 get ':url' =>'pages#show'
我应该如何从此路由重定向到 users#show 或 pages#show 操作之一?
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?
推荐答案
您首先需要一个代理操作,该操作会检查 url 是用户还是搜索数据库的页面,然后调用实际操作
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
类似的东西
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'
在应用程序控制器上
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
这篇关于Rails 中一条路线的两个动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!