views:

30

answers:

2

My app has the following models: user and watch_list. User has attributes id, name and WatchList has attributes user_id, friend_id.

class WatchList < ActiveRecord::Base
  belongs_to :user
  has_many :friends, :class_name => "User", :foreign_key => "friend_id"
end

class User < ActiveRecord::Base
  has_one :watch_list
  has_many :friends, :through => :watch_list

  def friends_with(friend_id)
    self.friends.each do |f|
      if f.id == friend_id
        return true
      end
    end
    return false
  end
end

For some reason when I use @current_user.friends_with(friend_id) I always get 'true' as a response. Any ideas why this won't work right? (I know @current_user works)

Thanks!

A: 

What are you trying to do with this method? Determining if a user is a friend with another (through watchlist)? By convention, in ruby, a method returning either true or false is ended by an interrogation mark…

You may use the include? Array method directly and do

@current_user.friends.include?(friend)

In this case, you use the friend object directly and not its id…

Or write a methode like the following:

I would try something like:

def has_a_friend_with_id?(friend_id)
  friends.map(&:id)include? friend_id
end

I renamed your method in order to have something more meaningful…

Yannis
Your answer makes a lot of sense, but I'm getting an error when using the method: Mysql::Error: Unknown column 'users.friend_id' in 'on clause': SELECT `users`.* FROM `users` INNER JOIN `watch_lists` ON `users`.friend_id = `watch_lists`.id WHERE ((`watch_lists`.user_id = 5))
scott
Are you using @current_user.has_a_friend_with_id?(user.id) ? You need to pass an integer (a user id) as attibute in the has_a_friend_with_id? method.
Yannis
Yes - I think it has something to do with my associations. A User has_many friends through a watch_list. A watch_list belongs_to a user and has_many friends (these friends are of class User).
scott
A: 

In the User model, try commenting out "has_one :watch_list", maybe this is preventing it from seeing more that one friend.

Tim