Christian Benseler
Christian Benseler

Reputation: 8065

Rails: build array with the value from a certain model attribute

I have an model called 'Notation' with the attributes 'name' and 'tag' In its controller there is an action that will return an json with the array with all 'tag' value (the 'tag' value from all model's records).

I have implemented this:

@tags = Notation.all.map{ |notation| notation.tag }
render json: @tags

this works, but I checked in the console and saw the SQL that has been queried:

SELECT "notations".* FROM "notations"

I was wondering if there is another way using ActiveRecord to query only the 'tag' attribute (mostly because of performances issues), or if this is something I do not have to worry about

Upvotes: 2

Views: 1380

Answers (2)

LHH
LHH

Reputation: 3323

Here are few ways to achieve this 1) Use pluck method

@tags = Notation.pluck(:tag)
render json: @tags

here is source https://apidock.com/rails/ActiveRecord/Calculations/pluck

2) use Select method

@tags = Notation.select(:tag).map(&:tag) (here convert ActiveRecord Relation object to Array)
render json: @tags

https://apidock.com/rails/ActiveRecord/QueryMethods/select

here is difference between pluck vs select, if you want to explore more. https://medium.com/@amliving/activerecords-select-pluck-3d5c58872053

Upvotes: 1

Sebastián Palma
Sebastián Palma

Reputation: 33420

When using all, then you're getting all the attributes from the model.

You could use select and ask only for the tag attribute, and you would give a query like "SELECT "notations"."tag" FROM "notations"" but you would get a Notation::ActiveRecord_Relation object type, and you should have to use map to get only an array with the needed attribute.

Visit.select(:name).map(&:name)

To skip the map part to create an array, you could use pluck like:

@tags = Notation.pluck :tag
render json: @tags

And this should also query only for the tag attribute from the Notation objects:

SELECT "notations"."tag" FROM "notations"

Upvotes: 2

Related Questions