Self-referencing has_many, :through-Collection of common programming errors

Here’s my User model:

class User < ActiveRecord::Base

  has_many :friends, :class_name => 'Friendship', :dependent => :destroy

end

Here’s my Friendship model:

class Friendship < ActiveRecord::Base

  belongs_to :user
  belongs_to :friend, :class_name => 'User', :foreign_key => 'friend_id'

  set_table_name :users_users
end

Now, I have a boolean attribute in the User model called *is_awesome*.

When I try to run this query:

User.find(1).friends.find(:all, :include => :users, :conditions => {:is_awesome => false})

I get the following error:

ActiveRecord::StatementInvalid: Mysql::Error: 
Unknown column 'users_users.is_awesome' in 'where clause': 
SELECT * FROM `users_users` 
WHERE (`users_users`.user_id = 1 AND (`users_users`.`is_awesome` = 0))

Any idea what’s going on?

  1. You have to change :condition to refer to user table, it should looks something like this:

    User.find(1).friends.find(:all, :include => :users, :conditions => "users.is_awesome IS FALSE")
    

Originally posted 2013-11-09 23:30:39.