Reputation: 289
I have the following classes with relations defined as follow:
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
User model has a field named: clan_id
Clan model has a field named: founder
What i would like its:
user.found_clan
=> resulting a clan object which has user
as founder
user.clan
=> resulting a clan object pointed by users clan_id
clan.founder
=> resulting an user object which clan.founder
points at
clan.users
=> resulting an array of all users
who have clan
pointed by user.clan_id
Upvotes: 1
Views: 49
Reputation: 54734
Your code has several issues:
class_name: 'Model'
as options, not class: Model
.founder_id
, not just founder
foreign_key
on both sides of the relationship (not primary_key
!)primary_key
and foreign_key
options (in this case Clan has_many :users
)This should work:
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
Upvotes: 2