0

モデル プロジェクトで正しく動作する 2 つのメソッドが定義されています。

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

これら2つをProjectモデルのスコープに変換すると

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"

これら2つのスコープステートメントを正しく書く方法を教えてください。ありがとう。

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 に答える