Preload has_one column value in ActiveRecord

Viewed 381

I have a has_one association where I really only need a single column's value:

class Item < ActiveRecord::Base
  has_one :last_view, -> {order(viewed_at.desc).limit(1).select(:viewed_at)

Is it possible to somehow only retrieve the column value (preferably without writing raw SQL when selecting from Item), and thus spare the association model instantiation costs, while still being able to preload the association?

To clarify, I'd like to be able to do this:

class Item < ActiveRecord::Base
  has_one :last_view, -> {order(viewed_at.desc).limit(1).pluck(:viewed_at)

And then this would only run one query:

Item.preload(:last_view).map(&:last_view)
0 Answers
Related