Finding object in array based on attribute
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 开发者_如何学C< 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!
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…
精彩评论