trnks_
trnks_

Reputation: 45

Why am I getting error FROM-clause entry for table error?

I am writing an app in Rails 4.2.1 using jRuby 1.7.16.1

I've got User and Project models. Project has one leader and many users through join model:

class Project < ActiveRecord::Base
  has_many :users_projects_join
  has_many :users, :through => :users_projects_join
  has_many :active_users, 
     -> { where(users_projects_join: {user_status: true}) }, 
     :through => :users_projects_join, 
     :source => :user

  belongs_to :leader, :class_name => 'User', :foreign_key => :leader_id
end

I wanted to have :active_users so I wrote the query showed above but it gives me

ERROR: missing FROM-clause entry for table "users_projects_join"
  Position: 167: SELECT "users".* FROM "users" 
    INNER JOIN "users_projects_joins" 
    ON "users"."id" = "users_projects_joins"."user_id" 
    WHERE "users_projects_joins"."project_id" = 20 
    AND "users_projects_join"."user_status" = 't'

But when I execute this query strictly in the Postgres it gives me all users with user_status true. I read that I need to add joins(:users_projects_join).where(...) but it didn't help.

Upvotes: 0

Views: 204

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118261

Try now :

class Project < ActiveRecord::Base
  has_many :users_projects_joins
  has_many :users, :through => :users_projects_joins
  has_many :active_users, 
     -> { where(users_projects_joins: {user_status: true}) }, 
     :through => :users_projects_joins, 
     :source => :user

  belongs_to :leader, :class_name => 'User', :foreign_key => :leader_id
end

Upvotes: 2

Related Questions