简体   繁体   English

Rails 4:从模型实例中选择多个属性

[英]Rails 4: select multiple attributes from a model instance

How do I fetch multiple attributes from a model instance, eg如何从模型实例中获取多个属性,例如

Resource.first.attributes(:foo, :bar, :baz)
# or
Resource.where(foo: 1).fetch(:foo, :bar, :baz)

rather than returning all the attributes and selecting them manually.而不是返回所有属性并手动选择它们。

You will use the method slice .您将使用方法slice

Slice a hash to include only the given keys.对哈希进行切片以仅包含给定的键。 Returns a hash containing the given keys.返回包含给定键的哈希。

Your code will be.你的代码将是。

Resource.first.attributes.slice("foo", "bar", "baz")
# with .where
Resource.where(foo: 1).select("foo, bar, baz").map(&:attributes)

How about pluck : pluck怎么样:

Resource.where(something: 1).pluck(:foo, :bar, :baz)

Which translates to the following SQL:转换为以下 SQL:

SELECT "resources"."foo", "resources"."bar" FROM, "resources"."baz" FROM "resources"

And returns an array of the specified column values for each of the records in the relation:并返回关系中每个记录的指定列值的数组:

[["anc", 1, "M2JjZGY"], ["Idk", 2, "ZTc1NjY"]] 

http://guides.rubyonrails.org/active_record_querying.html#pluck http://guides.rubyonrails.org/active_record_querying.html#pluck

Couple of notes:几点注意事项:

  • Multiple value pluck is supported starting from Rails 4, so if you're using Rails 3 it won't work.从 Rails 4 开始支持多值pluck ,因此如果您使用的是 Rails 3,它将无法工作。
  • pluck is defined on ActiveRelation, not on a single instnce. pluck是在 ActiveRelation 上定义的,而不是在单个实例上定义的。
  • If you want the result to be a hash of attribute name => value for each record you can zip the results by doing something like the following:如果您希望结果是每条记录的属性名称 => 值的哈希值,您可以通过执行以下操作来zip结果:

     attrs = [:foo, :bar, :baz] Resource.where(something: 1).pluck(*attrs).map{ |vals| attrs.zip(vals).to_h }

To Fetch Multiple has_one or belongs_to Relationships, Not Just Static Attributes.获取多个has_onebelongs_to关系,而不仅仅是静态属性。

To fetch multiple relationships, such as has_one or belongs_to , you can use slice directly on the instance, use values to obtain just the values and then manipulate them with a map or collect .要获取多个关系,例如has_onebelongs_to ,您可以直接在实例上使用slice ,使用values来获取值,然后使用mapcollect操作它们。

For example, to get the category and author of a book , you could do something like this:例如,要获取一bookcategoryauthor ,您可以执行以下操作:

book.slice( :category, :author ).values 
#=> #<Category id: 1, name: "Science Fiction", ...>, #<Author id: 1, name: "Aldous Huxley", ...>

If you want to show the String values of these, you could use to_s , like:如果要显示这些字符串的值,可以使用to_s ,例如:

book.slice( :category, :author ).values.map( &:to_s )
#=> [ "Science Fiction", "Aldous Huxley" ]

And you can further manipulate them using a join , like:您可以使用join进一步操作它们,例如:

book.slice( :category, :author ).values.map( &:to_s ).join( "➝" )
#=> "Science Fiction ➝ Aldous Huxley"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM