我在Rails中的模型之间查询时遇到了一些麻烦。我有Message
的课程belongs_to: booking
。我的目标是将active
范围添加到Message
,取决于Booking
范围。
class Booking < ActiveRecord::Base
has_one :event
has_many :messages
def self.active
includes(:event).
where('events.endtime >= ? AND status IS NOT ?'
Time.current.beginning_of_week,
statuses['canceled'])
end
end
class Message < ActiveRecord::Base
belongs_to :booking
belongs_to :person
self.active(person_id)
where(person_id: person_id).merge(Booking.active)
end
end
我想找到Message
指向特定Person
的关联Booking
为active
的{{1}}。因此,我希望在创建Booking.active
时使用Message.active
。
使用上述实现调用Message.active(1)
会返回以下错误:
Association named 'event' was not found on Message; perhaps you misspelled it?
我是否可以在Booking.active
的实施中使用Message.active
并返回获取Message
?
答案 0 :(得分:1)
如果您要为关联添加条件,您还需要加入,而不仅仅是merge
或include
,即以下内容应该有效:
class Booking < ActiveRecord::Base
# ...
def self.active
joins(:event).
where('events.endtime >= ? AND status IS NOT ?'
Time.current.beginning_of_week,
statuses['canceled'])
end
end
class Message < ActiveRecord::Base
# ...
self.active(person_id)
where(person_id: person_id).joins(:booking).merge(Booking.active)
end
end
关于此的文档不多,请参阅this以获取更多信息。