tmaximini
tmaximini

Reputation: 8503

Scope with join across two models not working in Rails 3.1

I have a time tracking application.

An Hour belongs_to a Project. And a Project belongs to a ProjectStatus and thus has a field project_status_id.

Now I want to scope my Hour model to filter all hours that belong to projects with a certain status, e.g. 2.

In my Project model I have this scope:

  #project.rb
  scope :continous, where(:project_status_id => '2')

In my Hour model I tried the following scope but it always returns an empty array, also I know there are hours that math my criteria:

  #hour.rb
  scope :intern, joins(:project) & Project.continous

also I think the generated SQL output on the console looks a little strange:

1.9.2-p180 :003 > Hour.intern
  Hour Load (104.5ms)  SELECT `hours`.* FROM `hours` INNER JOIN `projects` ON `projects`.`id` = `hours`.`project_id`
  Project Load (6.1ms)  SELECT `projects`.* FROM `projects` WHERE (project_status_id <> 2)
  Hour Load (95.9ms)  SELECT `hours`.* FROM `hours` INNER JOIN `projects` ON `projects`.`id` = `hours`.`project_id`
  Project Load (1.0ms)  SELECT `projects`.* FROM `projects` WHERE `projects`.`project_status_id` = 2
  Hour Load (92.6ms)  SELECT `hours`.* FROM `hours` 
 => [] 

Why is there one query with WHERE (project_status_id <> 2) and one with WHERE 'projects'.'project_status_id' = 2 ?

Is he trying to subtract the two from each other ? Any hints how to make this scope work.. ? thanks

Upvotes: 1

Views: 155

Answers (1)

Peter Brown
Peter Brown

Reputation: 51707

Not sure if this is the most elegant approach, but you can merge relation objects:

scope :intern, lambda { joins(:project).merge(Project.continous) }

Note that I'm wrapping it in a lambda so Project.continuous is not executed when the application loads. Also, this is the preferred way to define scopes in future versions of Rails.

Upvotes: 1

Related Questions