我想通過連接表獲取記錄數組。我想查找一個用戶的收藏夾是藍色的,但是「當前」。 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')
現在我得到這個錯誤「有一個錯誤: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
@NothingToSeeHere對不起,我有一個錯字。在那裏聲明,它應該是'收藏夾'(複數),因爲在那裏,你引用了實際的表名(在rails中它總是複數)。更新了答案。 –