具有联接表的ActiveRecord明确查询

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

  • 我需要在日期字段上执行where子句
  • 我需要加入2张桌子

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

我基本上需要结合以下两个答案:

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 
vcaonimav 回答:具有联接表的ActiveRecord明确查询

这是模棱两可的,因为两个表都具有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

本文链接:https://www.f2er.com/3105598.html

大家都在问