【问题标题】:Querying through a join table Rails 4 Postgres通过连接表查询 Rails 4 Postgres
【发布时间】:2015-10-06 19:29:44
【问题描述】:

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

用户.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') } 

类用户控制器

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')

【问题讨论】:

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


    【解决方案1】:

    关于这个:

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

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

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

    【讨论】:

    • 我现在收到此错误“有一个错误:PG::UndefinedTable: 错误:缺少表“收藏夹”第 1 行的 FROM 子句条目:...id”在哪里“user_favorites”。 "user_id" = $1 AND "favorite"."... ^ : 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 抱歉,我打错了。在 where 语句中,它应该是 favorites(复数),因为在 where 中,您引用的是实际表的名称(在 rails 中始终是复数)。更新了答案。
    【解决方案2】:

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

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

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

    【讨论】:

    • 我现在收到此错误“有一个错误:PG::UndefinedTable: 错误:缺少表“收藏夹”第 1 行的 FROM 子句条目:...id”在哪里“user_favorites”。 "user_id" = $1 AND "favorite"."... ^ : 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'"
    • 您确定在 where 子句中使用了表名吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-26
    • 1970-01-01
    • 2012-08-29
    • 2015-09-23
    • 2019-07-01
    • 1970-01-01
    • 2022-11-11
    相关资源
    最近更新 更多