0

Lets say I have a project model which has many members and many tasks.

class Project < ActiveRecord::Base
  has_many :memberships
  has_many :members, :through => :memberships, :class_name => 'User'
  has_many :tasks
end

When a task is created in the project, we keep a record of which user created it. Only users who are a member of the current project can

class Task < ActiveRecord::Base
  belongs_to :creator, :class_name => 'User'
  belongs_to :project
end

In my projects#show action, I want to find a project and display it along with it's members, tasks and their creators. I try to eager load these things in order to speed up the query.

Since I am eager loading the searches members, and tasks can only have a creator who is a member, am I right in thinking that I don't have to include the task's creator specifically?

In other words, can I do this:

Search.includes(:members, :tasks)

or should I do this:

Search.includes(:members, :tasks => :creator)
Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
David Tuite
  • 22,258
  • 25
  • 106
  • 176
  • I think you will need to explicitly include :creator otherwise it will query for it when you access the creator, because there is no way rails can know that creator is one of the already queried members. – Abid May 03 '12 at 22:28
  • @Abid It looks like you are correct. If you would like to move your comment into an answer I will accept it. – David Tuite May 23 '12 at 14:06

1 Answers1

1

I think you will need to explicitly include :creator otherwise it will query for it when you access the creator, because there is no way rails can know that creator is one of the already queried members

Abid
  • 7,149
  • 9
  • 44
  • 51