【发布时间】:2014-06-22 03:19:40
【问题描述】:
我有一个用户模型,我想通过使用 has_and_belongs_to_many 的自连接连接到它自己。我让它几乎按预期工作,除了我希望它以两种方式关联两个用户。
我的用户类:
class User < ActiveRecord::Base
...
has_and_belongs_to_many :friends,
autosave: true,
class_name: 'User',
join_table: :friendships,
foreign_key: :user_id,
association_foreign_key: :friend_user_id
...
end
我的迁移:
class CreateFriendships < ActiveRecord::Migration
def self.up
create_table :friendships, id: false do |t|
t.integer :user_id
t.integer :friend_user_id
end
add_index(:friendships, [:user_id, :friend_user_id], :unique => true)
add_index(:friendships, [:friend_user_id, :user_id], :unique => true)
end
def self.down
remove_index(:friendships, [:friend_user_id, :user_id])
remove_index(:friendships, [:user_id, :friend_user_id])
drop_table :friendships
end
end
我的问题:
user1 = User.find(1)
user2 = User.find(2)
user1.friends << user2
user1.reload.friends.exists?(user2) # true
user2.reload.friends.exists?(user1) # false <- My problem
我怎样才能让这种关系双向运作?由于在这种情况下友谊总是相互的,而关于 SO 的其他问题看起来应该是可能的,我希望最后两个陈述都返回 true。
【问题讨论】:
-
您也可以查看the solution我在 SO 上发布的类似问题。
标签: ruby-on-rails activerecord ruby-on-rails-4 rails-activerecord