4

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.