简体   繁体   English

在Rails 5 中从另一个模型中选择belongs_to 模型的有效方法?

[英]Efficent way to select belongs_to model from another Model, in Rails 5?

I have 2 models:我有 2 个模型:

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我想从我的消息表中选择最后 10 个联系人(作为对象数组,而不仅仅是 ID)

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?但是还有另一种更好的方法或 rails 方法来做到这一点吗?

EDIT I want to select the last 10 contacts from my messages table编辑我想从我的消息表中选择最后 10 个联系人

I would do this in one database query.我会在一个数据库查询中做到这一点。

Contact
  .distinct
  .joins(:messages)
  .order('messages.created_at DESC')
  .limit(10)

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:这将产生以下 SQL:

"SELECT  DISTINCT \"messages\".\"id\" FROM \"messages\"   ORDER BY \"messages\".\"created_at\" DESC LIMIT 10"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM