Rails Routes - 动态选择控制器 [英] Rails Routes - Select controller dynamically

查看:42
本文介绍了Rails Routes - 动态选择控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说,为了这个问题,我有两种用户类型:type1 &type2.我希望 Rails 根据显示的用户类型使用控制器/模块.例如:

Lets say, for the sake of the question, that I have two user types: type1 & type2. I want Rails to use a controller/module depending on the type of user that is being displayed. For example:

如果 User(id: 1, type: 'type1')type1User(id: 2, type: 'type2')type2,将:

If User(id: 1, type: 'type1') has type1 and User(id: 2, type: 'type2') has type2, going to:

/users/1

将选择 Type1::UsersController.然后去:

would select the Type1::UsersController. And going to:

/users/2

将选择 Type2::UsersController.

would select the Type2::UsersController.

这将允许我为每种类型使用不同的控制器和视图.

This will allow me to use different controllers and views for each type.

注意:我不希望 type 显示在 URL 中,我希望它是动态的.

Note: I don't want the type to be displayed in the URL, I want it to be dynamic.

推荐答案

正如 GoGoCarl 所说,这并不是真正的 Rails 做事方式.也就是说,让它发挥作用并不难.你可以在 routes.rb 中做这样的事情:

As GoGoCarl says, this isn't really the Rails way to do things. That said, it's not that difficult to get it to work. You can do something like this in routes.rb:

get 'users/:id', to: 'type1/users#show', constraints: lambda { |request| 
  _id = request.fullpath.gsub('/users/','').to_i
  # Note: there might be an easier way to get ID from the request object
  User.find(_id)._type == 'type1'
}
get 'users/:id', to: 'type2/users#show', constraints: lambda { |request| 
  _id = request.fullpath.gsub('/users/','').to_i
  User.find(_id)._type == 'type2'
}

在我的示例中,我已将您的 type 字段重命名为 _type(因为 Rails 使用 type 进行单表继承).我已经对此进行了测试,并且可以正常工作.

I've renamed your type field to _type in my example (because Rails uses type for Single Table Inheritance). I've tested this and it works as desired.

这篇关于Rails Routes - 动态选择控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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