开发者

How to dynamically choose field to return in Rails

开发者 https://www.devze.com 2023-02-08 10:14 出处:网络
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:

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 开发者_JS百科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


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"


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消