【问题标题】:Use 'includes' models inside SQL Rails queries在 SQL Rails 查询中使用“包含”模型
【发布时间】:2016-09-20 05:38:58
【问题描述】:

我有模型Task,它与用户表有关 - 作为受让人和报告者

class Task < ActiveRecord
  belongs_to :assignee, class_name: 'User'
  belongs_to :reporter, class_name: 'User'
end

在 sql 中,我想选择受让人具有特定名称的任务

Task.includes(:assignee, :reporter).where('assignee.first_name = ?', 'Filip')

但是这个查询引发了:

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "assignee"

我可以打电话

Task.includes(:assignee, :reporter).where('user.first_name = ?', 'Filip') 但它会返回受让人和报告者的记录

如何在仅引用受让人关系的where子句中添加条件?

【问题讨论】:

  • 出于好奇,model: 'User' 选项是什么?我认为应该是class_name: 'User',但可能是我遗漏了什么
  • @AndreyDeineko 很好,我的意思是 class_name。我是手写这个例子:)

标签: sql ruby-on-rails ruby postgresql ruby-on-rails-4


【解决方案1】:

如果Assignee's表名是assignees,可以这样写:

    Task.
      includes(:assignee, :reporter).
      where('assignees.first_name = ?','Filip').
      references(:users)

希望能帮到你。

【讨论】:

    猜你喜欢
    • 2021-06-08
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    相关资源
    最近更新 更多