以下是一些可能有用的资源:
我将总结在这些链接中找到的信息:
由于您描述了一个自我引用的多对多关系,因此您当然会得到一个连接表。通常情况下,连接表应该有一个明确的名称,以便Rails可以自动确定该表连接的模型,但是“自我引用”部分使得这有点棘手,但并不难。您只需要指定连接表的名称以及连接列即可。
您需要使用迁移创建此表,这个迁移可能看起来像这样:
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
我不确定是否有快捷的方法来创建这个表,但最简单的方法是使用rails g migration create_friendships
命令,并填写self.up
和self.down
方法。
然后在你的用户模型中,只需添加连接表的名称,如下所示:
class User < ActiveRecord::Base
has_and_belongs_to_many :friends,
class_name: "User",
join_table: :friendships,
foreign_key: :user_id,
association_foreign_key: :friend_user_id
end
你可以看到,虽然数据库中有一个连接表,但没有相关的连接模型。
请告诉我这是否适用于你。
User
对象数组吗? - Paul Richter