2017-02-20 27 views
0

在我的Rails 5應用程序中,我收到來自查詢的這個錯誤,但我不知道如何解決它。Rails - PG :: SyntaxError:錯誤:子查詢有太多列

PG::SyntaxError: ERROR: subquery has too many columns

我的控制器:

def index 
    @canvases = current_user.get_voted Canvas 
    @activities = PublicActivity::Activity.order("created_at desc").where(owner_id: current_user.friend_ids, owner_type: "User").or(PublicActivity::Activity.order("created_at desc").where(recipient_id: current_user.id)).or(PublicActivity::Activity.order("created_at desc").where("key = ? AND recipient_id in (?)", "canvas_product.create", @canvases)).paginate page: params[:page], per_page: 30 
end 

的錯誤是在此查詢的地方:

(PublicActivity::Activity.order("created_at desc").where("key = ? AND recipient_id in (?)", "canvas_product.create", @canvases)) 
+0

在猜測......'@ canvases'是一組實際的畫布,也許Rails沒有將這些解釋爲正確的ID ...嘗試將其改爲:'where(「key =?和()中的recipient_id,「canvas_product.create」,@ canvases.map(&:id))' - 如果這樣的話,那麼你就知道它就是這樣的 –

+0

就是這樣!謝謝!我應該這樣做,以限制@canvases只是在查詢之前的id(效率更高)?謝謝! – yellowreign

+0

我會創建一個答案並加上:) –

回答

1

貌似@canvases是一組實際的畫布,也許Rails是不是將這些解釋爲ID正確...

您可以轉換隻是IDS是這樣的:

where("key = ? AND recipient_id in (?)", "canvas_product.create", @canvases.map(&:id)) 

或者您可以使用pluck對聯想到挖出只需要例如IDS:

@canvas_ids = current_user.get_voted(Canvas).pluck(:id) 

(雖然這取決於如何get_voted被寫入)

+1

更好的是像'where(:recipient_id => @ canvases.select(:id))'如果'@ canvases'是一個關係,那麼AR會使用子查詢並將工作留在數據庫中。 –