【问题标题】:Converting methods in model to scope : Rails3将模型中的方法转换为范围:Rails3
【发布时间】:2023-03-29 18:25:01
【问题描述】:

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

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"

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

【问题讨论】:

    标签: ruby-on-rails-3 scope active-record-query


    【解决方案1】:

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

    无论如何,您的错误似乎来自您尝试调用名为“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")}
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-17
      • 2011-10-24
      • 1970-01-01
      • 1970-01-01
      • 2015-11-08
      相关资源
      最近更新 更多