4

I want to find a Blog by its :id, and then select only a couple of its attributes.

Example:

# Doesn't work and I don't know why
# I want to grab the first blog with this id, and then grab only selected attributes
blog = Blog.find(10).select(:id, :title, :date)

This post suggests to use where instead of find. But to my knowledge where in my scenario is inefficient because it continues searching the database for more matches even after it finds the only record I want to grab.

How can I specify to grab the first record it finds by the id, and then grab only the selected attributes?

Community
  • 1
  • 1
Neil
  • 4,578
  • 14
  • 70
  • 155

3 Answers3

8

blog = Blog.select(:id, :title, :date).find(1)

nsave
  • 984
  • 9
  • 27
3

@nsave's answer is probably your best bet.

If for whatever reason, you want to keep your order (of select going later), you can do the following:

blog = Blog.where(id: 10).select(:id, :title, :date).first

or

blog = Blog.where(id: 10).select(:id, :title, :date)[0]

Kalman
  • 8,001
  • 1
  • 27
  • 45
2

pick (Rails 6+)

Rails 6 introduced a new pick method.

So, now your problem can be solved as

Blog.where(id: 1).pick(:id, :title, :date)

It is even more efficient than

Blog.select(:id, :title, :date).find(1)

since, it will only load the column value(s), and will not load the ActiveRecord object.

For more details, please, follow this link to docs.

Also, there is a reference to the corresponding PR.

Marian13
  • 7,740
  • 2
  • 47
  • 51