This project is archived and is in readonly mode.

#3235 ✓duplicate
Greg Hazel

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 FROM users
User Load (0.0ms)  Mysql::Error: Column 'id' in where clause is ambiguous: SELECT users. FROM users 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: SELECT users. FROM users  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

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>

Pages