每天一剂Rails良药之Self-referential Many-to-Many Relationships

考虑一个UserStory,Person 1添加Person 2为好友,怎样让Person 2的好友列表中也有Person 1?
这里Person对自己Many-to-Many关联。

class AddPeopleAndTheirFriendsRelationship < ActiveRecord::Migration
  def self.up
    create_table :people do |t|
      t.column "name", :string
    end
    create_table :friendships do |t|
      t.column "person_id", :integer
      t.column "friend_id", :integer
    end
  end
  def self.down
    drop_table :people
    drop_table :friendships
  end
end

class Person < ActiveRecord::Base
  has_and_belongs_to_many :friends,
    :class_name => "Person",
    :join_table => "friendships",
    :association_foreign_key => "friend_id",
    :foreign_key => "person_id",
    :after_add => :be_friendly_to_friend,
    :after_remove => :no_more_mr_nice_guy
    def be_friendly_to_friend(friend)
      friend.friends << self unless friend.friends.include?(self)
    end
    def no_more_mr_nice_guy(friend)
      friend.friends.delete(self) rescue nil
    end
end

这里:after_add和:after_remove是不是有点filter的意思?

你可能感兴趣的:(UP,ActiveRecord,Rails)