根据属性查找数组中的对象

时间:2010-09-24 16:48:10

标签: ruby-on-rails arrays activerecord associations

我的应用有以下型号:user和watch_list。用户具有属性id,name和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工作)

谢谢!

1 个答案:

答案 0 :(得分:0)

你想用这种方法做什么?确定用户是否是另一个用户的朋友(通过监视列表)? 按照惯例,在ruby中,返回true或false的方法以询问标记结束......

您可以使用包含?直接使用数组方法并执行

@current_user.friends.include?(friend)

在这种情况下,您直接使用friend对象而不是其id ...

或者编写如下的方法:

我会尝试类似的事情:

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

我重命名了你的方法,以便有更有意义的东西......

相关问题