has_many中的最新has_one [英] Most recent has_one from a has_many

查看:69
本文介绍了has_many中的最新has_one的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带钥匙(域)的公司模型.我有一个联系模型,其中也有一个域.

I have a company model with a key (domain). I have a contact model which also has a domain.

我已经成功地在两者之间建立了has_many关系.

I have successfully setup a has_many relationship between these two.

has_many :contacts, class_name: 'Contact', primary_key: 'domain', foreign_key: 'domain'

每个联系人上都有一个 date 字段.我想要一种可以从 contacts 关系中获得最新联系人(按 date )的关系.

Each contact has a date field on it. I'd like a relationship which gets me the most recent contact (by date) from the contacts relationship.

这可能吗?

我知道我可以做类似的事情:

I'm aware I could do something like:

def most_recent_contact
  contacts.order('date desc null last').first
end

这是最好的方法吗?是 rails 方式吗?公开征求意见.

Is this the best way? Is it the rails way? Open to suggestions.

推荐答案

好吧,这似乎是一种方法,但是它不会重用"这种关系(它会重复).

Well, this seems to be ONE way, but it doesn't "reuse" the relationship (it repeats it)...

has_many :contacts, class_name: 'Contact', primary_key: 'domain', foreign_key: 'domain'
has_one  :most_recent_contact, -> { order date:  :desc }, class_name: 'Contact', primary_key: 'domain', foreign_key: 'domain'

这篇关于has_many中的最新has_one的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆