我有以下类,其关系定义如下:
class User < ActiveRecord::Base
belongs_to :clan
has_one :found_clan,class: Clan,foreign_key: 'founder'
end
class Clan < ActiveRecord::Base
has_many :users, primary_key: 'id', foreign_key: 'clan_id'
belongs_to :founder,class: User,primary_key: 'founder'
end
用户模型有一个名为clan_id
Clan模型有一个名为founder
我想要它:
user.found_clan
=&gt;产生一个具有user
founder
user.clan
=&gt;导致用户clan_id
clan.founder
=&gt;产生clan.founder
指向
clan.users
=&gt;生成由users
clan
的所有user.clan_id
数组
答案 0 :(得分:2)
您的代码有几个问题:
class_name: 'Model'
作为选项,而不是class: Model
。founder_id
命名,而不仅仅是founder
foreign_key
(而不是primary_key
!)primary_key
和foreign_key
选项(在本例中为Clan has_many :users
)这应该有效:
class User < ActiveRecord::Base
belongs_to :clan
has_one :clan_founded, class_name: 'Clan', foreign_key: 'founder_id'
end
class Clan < ActiveRecord::Base
has_many :users
belongs_to :founder, class_name: 'User', foreign_key: 'founder_id'
end