Rails: Load just one attribute not a whole model

Lets say I have a model, Foo, which is big and has lots of components. For a given Ajax query I’m only interested in one particular attribute, bar, which is a column in the foos table.Is there a simple way I could load just that attribute, and not bother with retrieving the rest of the record? For instance …

via Sql Databases Development » Search Results » ajax:

Rails: Load just one attribute not a whole model

Lets say I have a model, Foo, which is big and has lots of components. For a given Ajax query I’m only interested in one particular attribute, bar, which is a column in the foos table.
Is there a simple way I could load just that attribute, and not bother with retrieving the rest of the record? For instance if all I want to know is the bar for Foo with id#__, how could I retrieve that?
………………..

You can return only specific columns by calling the select method with a string containing the attributes you want to return. For your example:
Foo.select(‘bar’).first #Keep in mind that these objects will act like normal ActiveRecord objects but return nil for any field you did not select, so take care using this functionality.
You can call select on the class name itself or any Relation, so you can chain together the ActiveRecord calls you usually use like where, etc.
………………..

Foo.where().select(‘fieldname’)
Example
results = Foo.where(‘is_active = ?’, true).select(‘bar’)
Access the selected fields as:
results.map res returns an array of bar’s

For more info: Rails: Load just one attribute not a whole model

Sql Databases Development » Search Results » ajax

Rails: Load just one attribute not a whole model

Share this post:

Related Posts

Leave a Comment