2010-09-24 81 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

相关问题