0
1

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で外部キーとassociation名は同じにしない

Posted at

要約

  • belongs_to :nameforeign_key :nameが同じだと、その逆のhas_manyをとるときにどうがんばってもうまく取れなかった
  • 同じにしない
  • 外部キーには_idつける

詳細

  • 以下のコードだとto_messagesfrom_messagesがとれない
class User < ApplicationRecord
  has_many :to_messages, class_name: 'Message', foreign_key: 'to', dependent: :destroy
  has_many :from_messages, class_name: 'Message', foreign_key: 'from', dependent: :destroy
end

class Message < ApplicationRecord
  has_many :to, class_name: 'User', foreign_key: 'to'
  has_many :from, class_name: 'User', foreign_key: 'from'
end

>Message.last.to
=>#<User id: 373...>
>User.last.to_messages
=>[]
  • has_manyの名前を変えたらいけた
class Message < ApplicationRecord
  has_many :to_user, class_name: 'User', foreign_key: 'to'
  has_many :from_user, class_name: 'User', foreign_key: 'from'
end
  • そもそもforeign_key_idがいいね
  • 自分では慣例的にやらないけどレビューであがってくることはあるので覚えておく
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?