2010-09-24 80 views
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的作品)

謝謝!

回答

0

你想用這種方法做什麼?確定用戶是否與另一個朋友是朋友(通過關注列表)? 按照慣例,在ruby中,返回true或false的方法以詢問標記結束...

您可以使用include?陣列方法是直接做

@current_user.friends.include?(friend) 

在這種情況下,你直接而不是它的ID使用朋友的對象...

或寫梅索德類似如下:

我會嘗試這樣的:

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

我改名的方法,纔能有更有意義......

+0

你答案很有道理,但是在使用方法時出現錯誤: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

+0

您是否使用@ current_user.has_a_friend_with_id?(user.id)?你需要在has_a_friend_with_id中傳遞一個整數(一個用戶ID)作爲attibute?方法。 – Yannis 2010-09-24 17:55:42

+0

是的 - 我認爲這與我的社團有關。用戶has_many通過watch_list的朋友。 watch_list屬於用戶和has_many朋友(這些朋友是用戶類的)。 – scott 2010-09-24 17:58:02

相關問題