よしだです

プログラミングの勉強してます

belongs_toでclass_nameを指定した時の命名規則変化について

has_many throughでUserモデル、communities_usersモデル、Communityモデルがあった場合

 

中間モデルに

Belongs_to :user

Belongs_to :community

と書いた場合と

Belongs_to :user_id, class_name: "User"

Belongs_to :community_id, class_name: "Community"

と書いた場合で命名規則が変化するようです

 

具体的には

 

Belomgs_to :userと書いた場合、Userモデルでは

 

has_many :communities_users

has_many :communities, through: :communities_users, source: :community

と書けばいいですが

 

Belongs_to :user_id, class_name: "User"と書いた場合は

 

has_many :communities_users

has_many :communities, through: :communities_users, source: :community_id

と書く必要があるようです。