【问题标题】:Finding object in array based on attribute根据属性在数组中查找对象
【发布时间】:2010-09-24 16:48:10
【问题描述】:

我的应用有以下模型:user 和 watch_list。 User 有属性 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) 时,我总是得到“真”作为响应。任何想法为什么这不起作用? (我知道@current_user 有效)

谢谢!

【问题讨论】:

    标签: ruby-on-rails arrays activerecord associations


    【解决方案1】:

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

    您可以使用包含?数组方法直接做

    @current_user.friends.include?(friend)
    

    在这种情况下,您直接使用朋友对象而不是它的 id……

    或者写一个类似下面的方法:

    我会尝试类似:

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

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

    【讨论】:

    • 您的回答很有道理,但是我在使用该方法时遇到错误:Mysql::Error: Unknown column 'users.friend_id' in 'on clause': SELECT users .* FROM users INNER JOIN watch_lists ON users.friend_id = watch_lists.id WHERE ((watch_lists.user_id = 5))
    • 你在使用@current_user.has_a_friend_with_id 吗?(user.id)?您需要在 has_a_friend_with_id 中传递一个整数(用户 ID)作为属性吗?方法。
    • 是的——我认为这与我的联想有关。用户通过监视列表拥有_许多朋友。一个 watch_list 属于_to 一个用户和 has_many 朋友(这些朋友属于 User 类)。
    猜你喜欢
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多