Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4: select multiple attributes from a model instance

How do I fetch multiple attributes from a model instance, e.g.

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.

like image 346
DreamWalker Avatar asked Dec 06 '22 19:12

DreamWalker


2 Answers

You will use the method 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)
like image 83
Arup Rakshit Avatar answered Jan 05 '23 01:01

Arup Rakshit


How about pluck:

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

Which translates to the following 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

Couple of notes:

  • Multiple value pluck is supported starting from Rails 4, so if you're using Rails 3 it won't work.
  • pluck is defined on ActiveRelation, not on a single instnce.
  • 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:

    attrs = [:foo, :bar, :baz]
    Resource.where(something: 1).pluck(*attrs).map{ |vals| attrs.zip(vals).to_h }
    
like image 22
Dani Avatar answered Jan 04 '23 23:01

Dani