2

我遇到了一个棘手的挑战。让我解释一下我正在努力实现的目标。如果用户使用 Facebook 登录我的应用程序,我会抓取他们所有的 Facebook 好友 UID 并将其存储为用户“facebook_friends”。然后,一旦登录,用户会看到即将发生的事件列表,我想检查每个事件是否有任何参与者与用户的 facebook 朋友的 UID 匹配并将其突出显示给他们。

我选择创建 Event.rb 模型,如下所示:

class Event < ActiveRecord::Base

  #  id                  :integer(11)

  has_many :attendances, as: :attendable
  has_many :attendees

  def which_facebook_friends_are_coming_for(user)
    matches = []
    self.attendees.each do |attendee|
      matches << user.facebook_friends.where("friend_uid=?", attendee.facebook_id)
    end
    return matches
  end

end

你可以看到我已经创建了which_facebook_friends_are_coming_for(user)方法,但它让我觉得效率低得令人难以置信。当我从控制台运行它时,它确实可以工作,但是如果我尝试以任何形式(如 YAML)转储它,我会被告知can't dump anonymous module。我假设这是因为现在“匹配”持有者不是这样的类(当它应该是 FacebookFriends 时)。

必须有更好的方法来做到这一点,我喜欢一些建议。

作为参考,其他类如下所示:

class User < ActiveRecord::Base
  #  id                  :integer(11)

  has_many :attendances, foreign_key: :attendee_id, :dependent => :destroy
  has_many :facebook_friends

end


class FacebookFriend < ActiveRecord::Base
  #  user_id             :integer(11)
  #  friend_uid          :string
  #  friend_name         :string

  belongs_to :user

end


class Attendance < ActiveRecord::Base
  #  attendee_id         :integer(11)
  #  attendable_type     :string
  #  attendable_id       :integer(11)

  belongs_to :attendable, polymorphic: true
  belongs_to :attendee, class_name: "User"

end
4

1 回答 1

2

类似的东西怎么样:

def which_facebook_friends_are_coming_for(user)
  self.attendees.map(&:facebook_id) & user.facebook_friends.map(&:friend_uid)
end

& 运算符只是返回两个数组的交集

于 2013-01-23T15:34:17.027 回答