通过连接查询 table Rails 4 Postgres
Querying through a join table Rails 4 Postgres
我正在尝试通过连接 table 获取一组记录。我想找到所有蓝色的用户收藏夹,但 "current"。 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
用户Favorite.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') }
class 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" = AND (start_date <= '2015-10-06') AND ((end_date >= '2015-10-06' or end_date IS NULL)) AND (Favorite.color = 'blue')
如果我理解正确,你的 :blue
范围应该是这样的:
scope :blue, -> { joins(:favorite).where(favorites: { color: 'blue' }) }
在 joins
中您必须使用关联名称,而在 where
子句中您必须使用 table 名称。
关于这个:
scope :blue, -> { where('self.favorite.color = ?','blue') }
您似乎混淆了数据库和 ruby 语法。另一个问题是此时查询不知道 favorite
是什么,因为它还没有被加入。尝试这样的事情:
scope :blue, -> { joins(:favorite).where(favorites: {color: 'blue'}) }
我正在尝试通过连接 table 获取一组记录。我想找到所有蓝色的用户收藏夹,但 "current"。 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
用户Favorite.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') }
class 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" = AND (start_date <= '2015-10-06') AND ((end_date >= '2015-10-06' or end_date IS NULL)) AND (Favorite.color = 'blue')
如果我理解正确,你的 :blue
范围应该是这样的:
scope :blue, -> { joins(:favorite).where(favorites: { color: 'blue' }) }
在 joins
中您必须使用关联名称,而在 where
子句中您必须使用 table 名称。
关于这个:
scope :blue, -> { where('self.favorite.color = ?','blue') }
您似乎混淆了数据库和 ruby 语法。另一个问题是此时查询不知道 favorite
是什么,因为它还没有被加入。尝试这样的事情:
scope :blue, -> { joins(:favorite).where(favorites: {color: 'blue'}) }