Reputation: 617
I have 2 models:
Contact -> has_many :messages
and
Message -> belongs_to :contact
I want to select the last 10 contacts (as array of object, not only ids) from my messages table
this is my attempt (and it works fine):
Contact.where(id: Message.pluck(:contact_id).uniq.last(10))
BUt is there another better or rails way to do this?
EDIT I want to select the last 10 contacts from my messages table
Upvotes: 0
Views: 506
Reputation: 106802
I would do this in one database query.
Contact
.distinct
.joins(:messages)
.order('messages.created_at DESC')
.limit(10)
Upvotes: 3
Reputation: 1244
You could try the following query:
Contact.where(id: Message.distinct.order(created_at: :desc).limit(10).select(:id))
This would produce the following SQL:
"SELECT DISTINCT \"messages\".\"id\" FROM \"messages\" ORDER BY \"messages\".\"created_at\" DESC LIMIT 10"
Upvotes: 0