[英]Rails: has_one of a has_many association with criteria
我有一个实例方法,可以将其声明为has_one关系。 如何从has_many到has_one定义关系?
此方法有效:
class Facility
has_many :locations
has_many :events, though: :locations
def upcoming_event
events.
where('events.start_time >= ?', Time.zone.now).
order('events.start_time ASC').
first
end
end
这种关系没有:
has_one :upcoming_event, -> {
where('start_time >= ?', Time.zone.now).
order('start_time ASC')
}, through: :locations, class_name: "Event"
根据Meagar的建议,有一种替代方法可以适应您对组相关功能的偏爱:
class Facility
has_many :locations
has_many :events, though: :locations do
def upcoming
where('start_time >= ?', Time.zone.now).order('start_time ASC')
end
end
end
这清楚地表明,即将到来是关系上的方法,而不是事件模型上的方法。 它还允许您编写:
facility.events.upcoming
对我来说(这是一种观点),与facility.upcoming_events
相比,沟通意图和层次结构更为清晰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.