【问题标题】:ActiveRecord Unambiguous Query with Joining table带有连接表的 ActiveRecord 明确查询
【发布时间】:2019-11-14 02:49:14
【问题描述】:

我正在尝试组合两个常见的活动记录查询。

  • 我需要对日期字段执行 where 子句
  • 我需要加入 2 个表

由于我要加入他们,我需要指定列的表,两个表都有一个列,created_at

我基本上需要结合这2个答案:

ActiveRecord joins throwing Column in where clause is ambiguous error - Rails 5.1

    @projects = @projects.joins(:categories).where(categories: { id: params[:category_id] }) if params[:category_id].present?

Active Record - Find records which were created_at before today

MyModel.where("created_at < ?", 2.days.ago)

我现在拥有的是这样的:

Train.joins(:schedule).where('created_at >= ?', DateTime.now - 7.days)

返回:

Mysql2::Error: Column 'created_at' in where clause is ambiguous: SELECT 

【问题讨论】:

  • 您要在哪个表上使​​用 WHERE 子句?还是两者兼而有之?
  • 我正在尝试在火车上使用它

标签: ruby-on-rails ruby activerecord


【解决方案1】:

这是模棱两可的,因为两个表都有created_at,它不知道要看哪一个。

为了在具有相同列名的连接表上指定条件,您可以执行类似...

Train.joins(:schedule).where(trains: { created_at: DateTime.now - 7.days })

或者……

time_range = DateTime.now - 7.days
Train.joins(:schedule).where('trains.created_at' => time_range)

您也可以使用范围来完成同样的事情,也许是一种更简洁的方式。在加入之前,在Train 上实现 WHERE 子句可能会更好。

reference

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多