1
0

Railsのフォロー機能実装中にbelongs_toの書き方を間違えてActiveRecord::AssociationTypeMismatchエラーが出た話

Posted at

読んで欲しい人

  • belongs_toの書き方をちゃんとわかってない人
  • ActiveRecord::AssociationTypeMismatchエラー出た人
  • 過去の俺

動作環境

  • ruby 3.3.0
  • Rails 7.1.3.3

やってたこと:悪い例

フォロー機能を実装してました。

  • フォローする側:follower
  • フォローされる側:followed
user.rb
class User < ApplicationRecord
  has_many :active_relationships, class_name: 'Relationship', foreign_key: 'follower_id', dependent: :destroy, inverse_of: 'follower'
end

※ フォローされる側の実装はしていない

relationship.rb

# このファイルの記述が間違ってた。

class Relationship < ApplicationRecord
  belongs_to :follower_id, class_name: 'User'
  belongs_to :followed_id, class_name: 'User'
end
2024070560413_create_relationships.rb
# Relationshipsテーブルのマイグレーションファイル
class CreateRelationships < ActiveRecord::Migration[7.1]
  def change
    create_table :relationships do |t|
      t.integer :follower_id, null: false
      t.integer :followed_id, null: false

      t.timestamps
      t.index %i[follower_id followed_id], unique: true
    end
  end
end

ActiveRecord::AssociationTypeMismatchエラーの原因

relationship.rb
class Relationship < ApplicationRecord
  belongs_to :follower_id, class_name: 'User'
  belongs_to :followed_id, class_name: 'User'
end
  • belongs_to :follower_idではなくbelongs_to :follower
  • belongs_to :followed_idではなくbelongs_to :followed

です。

マイグレーションのカラム名を指定してました。

belongs_toの使用方法について

belongs_to(関連モデル名, scope=nil, オプション={})

  • belongs_toの第一引数は、関連するモデル名であり、idではない

感想・学び

  • そのコードの意味や正しい使用方法を知らないとロクなことがない
  • コードを記述する以上、人に説明できるコードを書くべき

以上です。

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