使用字符串输入引用模型 [英] Referencing Model with String input

查看:59
本文介绍了使用字符串输入引用模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我希望制作一个可以使用 type(string) 和 id(int) 查询所需对象的页面.

Lets say I wish to make a page that can query the desired object with type(string) and id(int).

/query?type=people&id=1

/query?type=people&id=1

会来接我

Person.find(1)

Person.find(1)

/query?type=cities&id=123

/query?type=cities&id=123

会来接我

City.find(123)

City.find(123)

但是,我在如何将字符串转换为所需的模型类方面遇到了问题.

However, I have problems as to how to translate strings into the desired model class.

我能想到的唯一方法是

case params[:type]
 when 'people'
  @object = Person.find(params[:id])
 when 'cities'
  @object = City.find(params[:id])
end

但是,如果我有更多类型的模型,这种方法会很成问题.

However, this method will be quite problematic if I have more types of models.

有没有更好的方法?

先谢谢你,

推荐答案

尝试:

klass = params[:type]
klass.singularize.classify.constantize.find(params[:id])

@object = params[:type].singularize.classify.constantize.find(params[:id])

这篇关于使用字符串输入引用模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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