如何在 Rails 中动态选择要返回的字段
我有一个 Ruby on Rails 应用程序,我希望能够动态选择返回数据库的字段。我的意思是:
假设我有一个名为 Dog 的数据库表,该表包含“id”、“name”、“color”字段。
如果我想获得狗#7的名字,我显然可以这样做:
d = Dog.find(7)
the_output = d.name
但是,我想要做的是动态选择为狗#7返回什么字段。因此,假设我已经定义:
the_field = "name"
我希望能够执行类似 call: 的操作,
d.(the_field)
并让它返回狗的名字。 (我在这里使用括号,因为在 MATLAB 中你可以这样做(我一直这样做)并且它有效,但在 Rails 中不起作用。)这样做的明显优点是我可以在其他地方程序设置 the_field = "color"
并让我的相同代码返回狗的颜色而不是名称。
我尝试这样做:
Dog.find(d.id, :select=>the_field)
但这返回一个 Dog 对象,而不仅仅是包含狗的名字的字符串。由于在代码中,我不知道正在调用哪个字段,因此我不确定如何提取包含我想要的字段的字符串。
所以希望这一切都是有道理的,希望有好心人知道如何做到这一点。
谢谢!
问
I have a Ruby on Rails application, and I would like to be able to dynamically choose what field to return to the database. Here's what I mean:
Suppose I have a database table called Dog and that table has fields of "id", "name", "color".
If I want to get dog #7s name, I could obviously just do:
d = Dog.find(7)
the_output = d.name
However, what I want to do is dynamically choose what field to return for dog #7. So suppose that I have defined:
the_field = "name"
I want to be able to do something like call:
d.(the_field)
and have it return the name of the dog. (I use parenthesis here, because in MATLAB you can do it this way (and I do all the time) and it works, but that doesn't work in Rails.) The obvious advantage to this is that I can then somewhere else in the program set the_field = "color"
and have my same code return the color of the dog instead of the name.
I tried doing this:
Dog.find(d.id, :select=>the_field)
but that returns a Dog object, not just the string containing the name of the dog. And since, in the code, I don't know which field is being called, I'm not sure how to extract just the string containing the field that I want.
So hopefully that all made sense, and hopefully some kind person knows how to do this.
Thanks!
Q
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这样的事怎么办?
What about something like this?
对于 Rails ActiveRecord 对象,您可以执行以下操作:
对于整个对象组,您可以执行以下操作
For rails activerecord objects you can do:
You for a whole group of objects you can do