2015-10-06 75 views
0

我想通過連接表獲取記錄數組。我想查找一個用戶的收藏夾是藍色的,但是「當前」。 User_Favorites可以過期。這就是我想:通過連接表查詢Rails 4 Postgres

User.rb

has_many :user_favorites, dependent: :destroy 
has_many :favorites, through: :user_favorites 

Favorite.rb

has_many :user_favorites, dependent: :destroy 
has_many :users, through: :user_favorites 

UserFavorite.rb

belongs_to :user 
belongs_to :favorite 

scope :current_as_of, -> (date) do 
    where('start_date <= ?',date). 
    where('(end_date >= ? or end_date IS NULL)', date) 
    end 

    scope :blue, -> { where('self.favorite.color = ?','blue') } 

類UsersController < ApplicationController的

def profile 
@user = User.find(params[:id]) 
@blue_favorites = @user.user_favorites.current_as_of(Date.today).blue.all 
end 

這是錯誤我得到:

There is an Error: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "favorite" 
LINE 1: ...d_date >= '2015-10-06' or end_date IS NULL)) AND (Favorite.co... 
                  ^
: SELECT "user_favorites".* FROM "user_favorites" WHERE "user_favorites"."user_id" = $1 AND (start_date <= '2015-10-06') AND ((end_date >= '2015-10-06' or end_date IS NULL)) AND (Favorite.color = 'blue') 

回答

2

的問候是:

scope :blue, -> { where('self.favorite.color = ?','blue') } 

它看起來像你混淆了數據庫和Ruby的語法。另一個問題是,此時的查詢不知道favorite是什麼,因爲它尚未加入。嘗試這樣的事情,而不是:

scope :blue, -> { joins(:favorite).where(favorites: {color: 'blue'}) } 
+0

現在我得到這個錯誤「有一個錯誤:PG :: UndefinedTable:錯誤:缺少表」最喜歡的「FROM-clause條目 LINE 1:... id」WHERE「user_favorites」。「user_id」= $ 1 AND 「...」 ^ :SELECT「user_favorites」。* FROM「user_favorites」INNER JOIN「favorites」ON「favorites」。「id」=「user_favorites」。「favorite_id」WHERE「user_favorites」。「user_id 「= $ 1 AND」favorite「。」color「='blue'」 – NothingToSeeHere

+0

@NothingToSeeHere對不起,我有一個錯字。在那裏聲明,它應該是'收藏夾'(複數),因爲在那裏,你引用了實際的表名(在rails中它總是複數)。更新了答案。 –

1

如果我理解正確的:blue範圍應該是這個樣子:

scope :blue, -> { joins(:favorite).where(favorites: { color: 'blue' }) } 

joins,你必須使用協會的名稱,而在where子句中,您必須使用表名稱。

+0

我得到這個錯誤,現在「有一個錯誤:PG :: UndefinedTable:錯誤:缺少FROM子句的表項‘最愛’ LINE 1:... ID」 WHERE「user_favorites」。「user_id」= $ 1 AND「favourite」。「... ^ :SELECT」user_favorites「。* FROM」user_favorites「INNER JOIN」favorites「ON」favorites「。」id「=」user_favorites「 「favorite_id」WHERE「user_favorites」。「user_id」= $ 1和「favorite」。「color」='blue'「 – NothingToSeeHere

+0

你確定你在where子句中使用表名嗎? – IngoAlbers