2
2

More than 3 years have passed since last update.

ArgumentErrorはActive Recordのメソッドが原因のときがあるよ【class_nameオプション】

Last updated at Posted at 2020-03-25

ある日こんなエラーが出ました

Image from Gyazo
???

直訳・・・

『You tried to define an association named transaction on the model Product, but this will conflict with a method transaction already defined by Active Record. Please choose a different association name.』

『モデルProductにtransactionという名前の関連付けを定義しようとしましたが、Active Recordによって既に定義されているメソッドトランザクションと競合します。 別の関連付け名を選択してください。』

はて?
どこでメソッド名が被ったのか一晩考えました・・・

原因

こちらのRailsドキュメントをみてびっくりしました。

元々定義されているActive Recordのメソッドに「transaction」があるんですね。

Image from Gyazo

修正

修正方法としては2つありました。

  1. テーブル名を変える
  2. class_nameオプションを使ってメソッド名を変える

今回はすでにかなり実装を進めていたのでclass_nameオプションを使用することにしました。

class_nameオプションは普通は同じモデルを参照する外部キーを2つ以上もたせたいときに使用するそうです。

(使用例)

    belongs_to :buyer, class_name: 'User', foreign_key: 'buyer_id'
    belongs_to :seller, class_name: 'User', foreign_key: 'seller_id'

今回はメソッド名を「トランザクション」を「トレード」に。

product.rb
class Product < ApplicationRecord
  belongs_to :user
  has_one :trade, class_name:"Transaction", dependent: :destroy
end
transaction.rb
class Transaction < ApplicationRecord
  belongs_to :user, optional: true
  belongs_to :product, optional: true
end
user.rb
class User < ApplicationRecord
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable
  has_many :products
  has_many :trade, class_name:"Transaction", foreign_key: "transaction_id"
end

無事解決〜!

次回から肝に命じます・・・

参考

Railsガイド
railsアソシエーションオプションのメモ
Railsドキュメント

2
2
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
2
2