【发布时间】:2019-02-18 07:42:00
【问题描述】:
我有以下关联:
mobile_application.rb
has_many :events
事件.rb
belongs_to :mobile_application
以下运行正常:
MobileApplication.includes(:events)
#=> MobileApplication Load (1.6ms) SELECT `mobile_applications`.* FROM `mobile_applications` ORDER BY created_at desc
# Event Load (1.3ms) SELECT `events`.* FROM `events` WHERE `events`.`mobile_application_id` IN (746, 745, 744, ....
但是当我尝试以下方法时,
MobileApplication.includes(:events).where("events.expiry_date >= ?", Time.zone.now)
它会抛出一个错误:
MobileApplication Load (1.2ms) SELECT `mobile_applications`.* FROM `mobile_applications` WHERE (events.expiry_date >= '2019-02-18 07:34:40.738517') ORDER BY created_at desc
Mysql2::Error: Unknown column 'events.expiry_date' in 'where clause': SELECT `mobile_applications`.* FROM `mobile_applications` WHERE (events.expiry_date >= '2019-02-18 07:34:40.738517') ORDER BY created_at desc
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'events.expiry_date' in 'where clause': SELECT `mobile_applications`.* FROM `mobile_applications` WHERE (events.expiry_date >= '2019-02-18 07:34:40.738517') ORDER BY created_at desc
更新
请建议我如何过滤它。使用 references 也会引发以下错误,并且与 Marek Lipka 提供的答案相同,
ActiveRecord::StatementInvalid: Mysql2::Error: Column 'created_at' in
order clause is ambiguous: SELECT `mobile_applications`.`id` AS t0_r0,
`mobile_applications`.`name` AS t0_r1, ...
我猜这是由于模型中存在的default_scope 创建的列不明确,以便按两个关联表中都存在的created_at 对其进行排序。
【问题讨论】:
-
好像和引用无关,
events表没有expiry_date列。你运行迁移了吗? -
@Sid 是的,我得到了同样的参考错误,这是我从 Marek Lipka 提供的解决方案中得到的。更新问题!
标签: ruby-on-rails ruby ruby-on-rails-4 activerecord