jeudi 3 mai 2018

Rails eager load custom has_many on index

Ruby 2.1, Rails 3.2
I've got this relationship in my project model

scope :active, -> { where( deleted_at: nil ) }
has_many :foremen, class_name: "ProjectsUser",  conditions: ['current_foreman = 1']

in the controller:

@projects = Project.includes(:foremen).active

which generates this SQL

ProjectsUser Load (3.3ms)  SELECT `projects_users`.* FROM `projects_users` WHERE `projects_users`.`project_id` IN (122, 130, ...etc.) AND ( current_foreman = 1)

but when i call the relationship in the view...

<% @projects.each do |project| %>
  <%= project.foremen %>
<% end %> 

it runs another SQL query each time.

ProjectsUser Load (2.5ms)  SELECT `projects_users`.* FROM `projects_users` WHERE `projects_users`.`project_id` = 122 AND (current_foreman = 1 )
ProjectsUser Load (2.5ms)  SELECT `projects_users`.* FROM `projects_users` WHERE `projects_users`.`project_id` = 130 AND (current_foreman = 1 )
ProjectsUser Load (2.5ms)  SELECT `projects_users`.* FROM `projects_users` WHERE `projects_users`.`project_id` = 151 AND (current_foreman = 1 )
etc...

is am i misunderstanding something? shouldn't these records already be loaded?
how do I write this so it only runs one query for the ProjectsUser?

Aucun commentaire:

Enregistrer un commentaire