Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Activerelation skips where() in some scopes

#6633

Hi,

When trying to chain scopes with joins() and where() relations, it appears that some where conditions are ignored if I use the model's relation's name. Here is a concrete example of the problem.

My models are
class Album < ActiveRecord::Base
has_many :photos, :dependent => :destroy end
class Photo < ActiveRecord::Base
belongs_to :album end

===== Case 1 With scopes written like below, I get a correct SQL but it's incomplete, missing my where() filters. The where method is called with ":albumS"

class Photo < ActiveRecord::Base
scope :photo, lambda { |name| where(:name => name.downcase) } scope :album, lambda { |name| joins(:album).where(:albums => {:name => name.downcase}) } end

irb(main):134:0> Photo.photo('ppp').album('aaaaa').to_sql
=> "SELECT photos.* FROM photos INNER JOIN albums ON albums.id = photos.album_id WHERE (albums.name = 'aaaaa')"

Here, the filter on album.name is ok, but we're missing the filter on photo.name from the :photo scope, table names are OK

===== Case 2 With scopes written like below, I get an incorrect SQL query but missing my where() filters. The where method is called with ":albumS"

class Photo < ActiveRecord::Base
scope :photo, lambda { |name| where(:name => name.downcase) } scope :album, lambda { |name| joins(:album).where(:album => {:name => name.downcase}) } end

irb(main):136:0> Photo.photo('ppp').album('aaaaa').to_sql
=> "SELECT photos.* FROM photos INNER JOIN albums ON albums.id = photos.album_id WHERE (photos.name = 'ppp') AND (album.name = 'aaaaa')"

Now, we find both filters on album.name AND on photo.name, but the table names are not correct!

===== Am I doing something wrong in those situations?

Thanks

Reported by bmconseil · March 27th, 2011 @ 08:40 PM

State: new
Milestone: none
Assigned to: nobody
Importance: none

Activity

No comments yet.