0
我的應用程序有以下模型:user和watch_list。用戶具有屬性id,名稱和WatchList具有屬性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
由於某些原因,當我使用@ current_user.friends_with(friend_id)時,我總是得到'true'作爲響應。任何想法,爲什麼這不會正常工作? (我知道@current_user的作品)
謝謝!
你答案很有道理,但是在使用方法時出現錯誤:Mysql :: Error:'on子句'中的未知列'users.friend_id':SELECT'users'。* FROM'users' INNER JOIN' watch_lists' ON'users'.friend_id ='watch_lists'.id WHERE((''watch_lists'.user_id = 5)) – scott 2010-09-24 17:49:42
您是否使用@ current_user.has_a_friend_with_id?(user.id)?你需要在has_a_friend_with_id中傳遞一個整數(一個用戶ID)作爲attibute?方法。 – Yannis 2010-09-24 17:55:42
是的 - 我認爲這與我的社團有關。用戶has_many通過watch_list的朋友。 watch_list屬於用戶和has_many朋友(這些朋友是用戶類的)。 – scott 2010-09-24 17:58:02