1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails belongs_toの関連カラム名し指定する

Posted at

以下のようなモデルがある場合

class User < ApplicationRecord
  self.table_name = 'wifi_agency_users'
  belongs_to :agency
end

class Agency < ApplicationRecord
  self.table_name = 'wifi_agencies'
  has_many :users
end

スキーマはこんな感じです

User(id: integer, email: string, wifi_agent_id: integer, created_at: datetime, updated_at: datetime)

User.last.agencyで該当ユーザが所属している代理店を取得したいですが、Railsはデフォルトでuser.agency_idagency.idを紐付けるので、何も取得できないです。スキーマを見るとagency_idは存在しないから。でもwifi_agent_idっていうのがあるので、これと紐付けたい!

こういう風に外部キーをしてするだけでOKです!

class User < ApplicationRecord
  self.table_name = 'wifi_agency_users'
  belongs_to :agency, foreign_key: 'wifi_agent_id'
end

そもそも前の人がagencyモデル作る時wifi_agencyにしたら楽なのに!!ヽ(`Д´メ)ノ プンスカ!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?