Ruby on Rails - ArgumentError(用至少一个字段调用它):

时间:2017-10-28 20:14:02

标签: sql ruby-on-rails ruby postgresql

我正在尝试复制ActiveRecords模型中的以下查询,目前位于Ticket

SELECT COUNT(*)
FROM tickets
WHERE tickets.status = 'open' AND (SELECT COUNT(*) FROM messages INNER JOIN users ON messages.user_id = users.id WHERE messages.commentable_id = tickets.id AND users.admin = true) = 0

我有一个按opened状态过滤的范围:

scope :opened, -> { where(status: 'open') }

现在我创建了另一个范围unanswered来使用它:

  scope :unanswered, -> {
    opened.all.where(select.joins('INNER JOIN users ON messages.user_id = users.id').where('messages.commentable_id = tickets.id AND users.admin = true').count.zero?)
  }

然后它给了我这个错误:

Completed 500 Internal Server Error in 31ms (ActiveRecord: 5.5ms)

ArgumentError (Call this with at least one field):

我错过了什么?

1 个答案:

答案 0 :(得分:1)

如果您按照以下方式说出查询:

SELECT COUNT(DISTINCT t.id)
FROM tickets t LEFT JOIN
     messages m
     ON m.commentable_id = t.id LEFT JOIN
     users u
     ON m.user_id = u.id AND u.admin = true
WHERE t.status = 'open' AND u.id IS NULL;

然后也许变换会更容易。