Rails 中一条路线的两个动作 [英] Two actions for one route in Rails

查看:36
本文介绍了Rails 中一条路线的两个动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的问题:
我有两个模型:用户页面.
用户页面具有url字段.
所以我有路线
get ':url' =>'users#show'get ':url' =>'pages#show'
我应该如何从此路由重定向到 users#showpages#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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆