通过连接表查询Rails 4 Postgres

问题描述:

我想通过连接表获取记录数组。我想查找一个用户的收藏夹是蓝色的,但是“当前”。 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') 

的问候是:

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中它总是复数)。更新了答案。 –

如果我理解正确的: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