Reputation: 31064
So in Rails 3.x I used to be able to say:
id = 123
book = Book.find(id, select: ['title', 'description'])
and get back a Book that had only those fields that I specified. This was really handy as it allowed me to exclude certain large columns from my queries, yet still get back working ActiveRecord entities. Especially useful in a heavily de-normalized DB situation.
Now in Rails 4 this comes with a warning:
[WARN] DEPRECATION WARNING: Passing options to #find is deprecated.
Please build a scope and then call #find on it.
I can't quite seem to figure out the syntax for specifying column selection for a scope, so I end up with:
scope :my_find_by_id, -> id { where(id: id)}
and then calling it like:
Book.my_find_by_id(id).select(['title', 'description']).first
which seems rather verbose and silly. Is there a more idiomatic way to acomplish this in Rails 4?
Upvotes: 0
Views: 1326
Reputation: 231
Just call the select method before find:
Book.select(:title, :description).find(id)
Upvotes: 1
Reputation: 8604
You can use select
method to get title
and description
:
With scope:
scope :my_find_by_id, ->(id) { where(id: id).first }
Book.my_find_by_id(id).select(:title, :description)
Upvotes: 0