通过连接表查询Rails 4 Postgres

时间:2015-10-06 19:29:45

标签: ruby-on-rails postgresql ruby-on-rails-4 jointable

我试图通过连接表获取记录数组。我想找到所有用户的收藏夹是蓝色的,但这是“当前的”。 User_Favorites可以过期。这就是我正在尝试的:

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&lt; 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 个答案:

答案 0 :(得分:2)

关于这个:

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

看起来你正在混淆数据库和ruby语法。另一个问题是,此时查询不知道favorite是什么,因为它还没有加入。尝试这样的事情:

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

答案 1 :(得分:1)

如果我理解正确,您的:blue范围应如下所示:

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

joins中,您必须在where子句中使用关联名称,您必须使用表名。