This project is archived and is in readonly mode.
default scoping and associations
Reported by Greg Hazel | September 19th, 2009 @ 03:41 PM
Consider the following:
class User < ActiveRecord::Base
has_many :friends,
:foreign_key => 'user_id',
:class_name => 'Friendship'
end
User.scoped(:conditions => "id != 7").find_each do |user|
p user.friends
end
The result is:
User Load (1.0ms) SELECT * FROM
users WHERE (users.id >= 0) AND (id != 7) ORDER BY users.id ASC LIMIT 1000 User Columns (5.0ms) SHOW FIELDS FROMusers
User Load (0.0ms) Mysql::Error: Column 'id' in where clause is ambiguous: SELECTusers
. FROMusers
INNER JOIN friendships ON users.id = friendships.user_id WHERE (friendships
.friend_id = 1) AND (id != 7) ORDER BY users.id ASC LIMIT 1000 ActiveRecord::StatementInvalid: Mysql::Error: Column 'id' in where clause is ambiguous: SELECTusers
. FROMusers
INNER JOIN friendships ON users.id = friendships.user_id WHERE (friendships
.friend_id = 1) AND (id != 7) ORDER BY users.id ASC LIMIT 1000
Ignoring that I could have specified "users.id" - I used that example to show an error. Isn't it a bit strange for the current scope of the find_each to carry through to associations? Imagine something more exclusive like:
User.males.find_each do |user|
p user.female_friends
end
That would find nothing and not raise an error!
Comments and changes to this ticket
-
CancelProfileIsBroken September 25th, 2009 @ 11:59 AM
- Tag changed from activerecord to activerecord, bugmash
-
dira September 27th, 2009 @ 11:02 AM
+1 - applying the conditions of the scope is clearly a bug
verified
-
dira September 27th, 2009 @ 11:07 AM
I've attached a patch. This test applies on master and shows the bug.
-
William Gray October 14th, 2009 @ 03:46 PM
find_each doesn't just have this problem when used with a scope, it adds any :conditions used to called associations, like so:
User.find_each(:conditions => {:sex => 'male'}) do |user| p user.female.friends end
this would also return nothing, as the condition :sex => 'male' gets added to the call to user.female.friends.
-
Daniel Guettler October 26th, 2009 @ 02:39 AM
- Tag changed from activerecord, bugmash to activerecord, bugmash, patch, tests
The attached patch contains the tests Dira added plus the changes needed to make it pass. Basically it adds an empty hash to the scoped_methods before yielding records and removes it again after the yield.
-
Matt Jones October 26th, 2009 @ 03:22 AM
- State changed from new to duplicate
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
<h2 style="font-size: 14px">Tickets have moved to Github</h2>
The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>