0

我在我的模型项目中定义了两种正常工作的方法。

1.  def completed(user)
         Project.find_by_sql(["Select p.id from bids b LEFT JOIN tasks t ON b.task_id=t.id LEFT  JOIN projects p ON p.id = t.project_id where(b.bidder_id=? and b.status=? and p.status=?) group by p.id", user.id, 'ACCEPTED', 'COMPLETE']).count
    end

2.   def current(user)
        Project.find_by_sql(["Select p.id from bids b LEFT JOIN tasks t ON b.task_id=t.id LEFT JOIN projects p ON p.id = t.project_id where(b.bidder_id=? and b.status=? and p.status in ('LAUNCHED', 'CONFIRM', 'STAFFED', 'OVERDUE')) group by p.id", user.id, 'ACCEPTED']).count
    end

当我将这两个转换为项目模型中的范围时

1. `scope :completed, proc{|user| joins("LEFT JOIN tasks t ON t.project_id=projects.id LEFT JOIN bids b ON b.task_id=t.id where(b.bidder_id='#{user.id}' and b.status='ACCEPTED' and p.status='#{COMPLETE_STATUS}')").count("DISTINCT p.id")}`

2. `scope :current, proc{|user| joins("LEFT JOIN tasks t ON t.project_id=projects.id LEFT JOIN bids b ON b.task_id=t.id where(b.bidder_id='#{user.id}' and b.status='ACCEPTED' and p.status IN ('#{LAUNCHED_STATUS}', '#{CONFIRM_STATUS}', '#{STAFFED_STATUS}', '#{OVERDUE_STATUS}')) group by p.id").count("DISTINCT p.id")}`

我收到错误消息:ActionView::Template::Error (PG::Error: ERROR: missing FROM-clause entry for table "p"

请建议我,如何正确编写这两个范围声明。谢谢。

4

1 回答 1

0

我不认为范围是产生计数的更好解决方案,因为使用范围是为了获得过滤的对象列表。

无论如何,您的错误似乎来自您尝试调用名为“p”的表。“p”不存在,因为这是您的方法中的别名,您尚未在您的范围内声明。

要解决这个问题,您只需将“p”替换为“projects”。

scope :completed, proc{|user| joins("LEFT JOIN tasks t ON t.project_id=projects.id LEFT JOIN bids b ON b.task_id=t.id where(b.bidder_id='#{user.id}' and b.status='ACCEPTED' and projects.status='#{COMPLETE_STATUS}')").count("DISTINCT projects.id")}
scope :current, proc{|user| joins("LEFT JOIN tasks t ON t.project_id=projects.id LEFT JOIN bids b ON b.task_id=t.id where(b.bidder_id='#{user.id}' and b.status='ACCEPTED' and projects.status IN ('#{LAUNCHED_STATUS}', '#{CONFIRM_STATUS}', '#{STAFFED_STATUS}', '#{OVERDUE_STATUS}')) group by projects.id").count("DISTINCT projects.id")}

我希望这有帮助

于 2013-01-07T13:00:36.260 回答