Eki Eqbal
Eki Eqbal

Reputation: 6057

Rails Eager loading (includes) and where clause is not working?

I'm using Rails 4.1 and my Models something like:

Client has_many TicketLists
TicketList has many projects

Now I'm trying to use eager loading in Client model something like:

class Client < ActiveRecord::Base
  def ticket_lists_with_project_id(project_id)
    ticket_lists.includes(:projects).where("projects.id = ?", project_id)
  end  
end  

And when I do:

Client.find(2).ticket_lists_with_project_id(1)
  Client Load (1.7ms)  SELECT  "clients".* FROM "clients"  WHERE "clients"."is_destroyed" = 'f' AND "clients"."is_closed" = 'f' AND "clients"."id" = $1 LIMIT 1  [["id", 2]]
PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "projects"
LINE 1: ...d" = 'f' AND "ticket_lists"."client_id" = $1 AND (projects.i...
                                                             ^
: SELECT "ticket_lists".* FROM "ticket_lists"  WHERE "ticket_lists"."is_destroyed" = 'f' AND "ticket_lists"."client_id" = $1 AND (projects.id = 1)
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "projects"
LINE 1: ...d" = 'f' AND "ticket_lists"."client_id" = $1 AND (projects.i...

Upvotes: 2

Views: 5872

Answers (3)

Arup Rakshit
Arup Rakshit

Reputation: 118299

Try the below :

class Client < ActiveRecord::Base
  def ticket_lists_with_project_id(project_id)
    ticket_lists.includes(:projects)
                .where("projects.id = ?", project_id)
                .references(:projects)
  end  
end

It will work. If you want to add conditions to your included models you’ll have to explicitly reference them. Also note that includes works with association names while references needs the actual table name.

Upvotes: 11

Surya
Surya

Reputation: 16022

Instead of this:

ticket_lists.includes(:projects).where("projects.id = ?", project_id)

do this:

ticket_lists.joins(:projects).where("projects.id = ?", project_id)

Since you're using Rails 4, you can make it look more cuter:

ticket_lists.joins(:projects).where(projects: {id: project_id})

Upvotes: 4

Vrushali Pawar
Vrushali Pawar

Reputation: 3803

This may help you:

Client.includes(:ticket_lists => :projects).where("clients.id = ? ", 2)

OR

class Client < ActiveRecord::Base
  def ticket_lists_with_project_id(project_id)
    Client.includes(:ticket_lists => :projects).where("projects.id = ?", project_id)
  end  
end 

Upvotes: 1

Related Questions