简体   繁体   中英

Querying through a join table Rails 4 Postgres

I am trying to get an array of records through a join table. I want to find All of one User's Favorites that are Blue, but that are "current". User_Favorites can expire. This is what I'm trying:

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

class UsersController < ApplicationController

def profile
 @user = User.find(params[:id])
 @blue_favorites = @user.user_favorites.current_as_of(Date.today).blue.all
end

This is the error I get:

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

in regards to this:

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

It looks like you're mixing up database and ruby syntax. The other problem too is that the query, at this point, has no idea what favorite is because it hasn't been joined yet. Try something like this instead:

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

If I understand it correctly your :blue scope should look something like this:

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

In the joins you have to use the association name while in the where clause you have to use the table name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM