LogofaT
LogofaT

Reputation: 289

Rails relation for 3 models

I have 3 models which look like these:

class User < ActiveRecord::Base
 belongs_to :Clan
end

class Clan < ActiveRecord::Base
 has_many :users, primary_key: 'id', foreign_key: 'clan_id'
 belongs_to :clan_lvl
end

class ClanLvl < ActiveRecord::Base
 has_one :clan, primary_key: 'id', foreign_key: 'lvl_id'
end

Class User has clan_id and class Clan has lvl_id so I think my realation should be good.

And I can access data like current_user.clan.something but it seems that rails cant make the relation to the third model because current_user.clan.clan_lvl is always nil.

Any suggestions?

Upvotes: 0

Views: 31

Answers (1)

Anezio Campos
Anezio Campos

Reputation: 1555

Try this:

class User < ActiveRecord::Base
 belongs_to :clan
end

class Clan < ActiveRecord::Base
 has_many :users
 belongs_to :clan_lvl, foreign_key: 'lvl_id'
end

class ClanLvl < ActiveRecord::Base
 has_one :clan, foreign_key: 'lvl_id'
end

Upvotes: 1

Related Questions