在轨道和mongoid中观察一个场

时间:2012-11-28 12:55:01

标签: ruby-on-rails mongoid observers

我有User模型和FollowingFollower

用户模型

has_and_belongs_to_many :followers, class_name: 'User', inverse_of: :following
has_and_belongs_to_many :following, class_name: 'User', inverse_of: :followers

关注

has_and_belongs_to_many :followers, class_name: 'User', inverse_of: :following

has_and_belongs_to_many :followings, class_name: 'User', inverse_of: :followers

我有一个UserObserver应该会看到用户follower_ids是否已更改,然后将其添加到用户Activities

那么我该如何仅在follower_ids中观看更改并让最新用户id加入activities

1 个答案:

答案 0 :(得分:2)

我认为在这种情况下,最佳选择是封装在方法中添加新关注者的逻辑,并且,在此方法中,您可以触发任何您想要的内容:

#encoding: utf-8
class User
  include Mongoid::Document
  field :followers, type: Array
  attr_readonly :followers

  def add_new_follower(new_follower)
    unless followers.include?(user) 
      followers << user 
      trigger_added_follower_observers(user)
    end
  end

  private
  def trigger_added_follower_observers(new_follower)
    # trigger the stuff you want
  end
end

还有其他选项,例如使用ruby的Observable模块(http://www.ruby-doc.org/stdlib-1.9.3/libdoc/observer/rdoc/Observable.html),MongoID观察者(http:// mongoid.org/en/mongoid/docs/callbacks.html#observers),或者before_save hook,但恕我直言,我认为上面的代码是你最好的选择,而不会“伤害”你的模型。

希望它有所帮助。