LogofaT
LogofaT

Reputation: 289

Rails complicated relations

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

Answers (1)

Patrick Oscity
Patrick Oscity

Reputation: 54734

Your code has several issues:

  1. The Rails association helpers take class_name: 'Model' as options, not class: Model.
  2. You should name your founder column founder_id, not just founder
  3. When you want to specify a table column for joins, you must use foreign_key on both sides of the relationship (not primary_key!)
  4. For associations that stick to Rails' naming conventions, you do not need to supply the 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

Related Questions