如何在 Rails 中动态选择要返回的字段

发布于 2024-10-15 18:43:44 字数 736 浏览 7 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

メ斷腸人バ 2024-10-22 18:43:44

像这样的事怎么办?

class Dog < ActiveRecord::Base
  def self.query_field(id, field)
    find(id).send(field)
  end
end

field = :name
Dog.query_field(7, field) # "Roscoe"
field = :color
Dog.query_field(7, field) # "brown"

What about something like this?

class Dog < ActiveRecord::Base
  def self.query_field(id, field)
    find(id).send(field)
  end
end

field = :name
Dog.query_field(7, field) # "Roscoe"
field = :color
Dog.query_field(7, field) # "brown"
木格 2024-10-22 18:43:44

对于 Rails ActiveRecord 对象,您可以执行以下操作:

field = :name
d = Dog.find(7)
d[field]

对于整个对象组,您可以执行以下操作

field = :name
Dog.where(some_sql_query).pluck(field)

For rails activerecord objects you can do:

field = :name
d = Dog.find(7)
d[field]

You for a whole group of objects you can do

field = :name
Dog.where(some_sql_query).pluck(field)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文