我有一個型號名稱 ID,但出現此錯誤:ArgumentError (You tried to define an association named id on the model User, but this will conflict with a method id already defined by Active Record. Please choose a different association name.)
這是錯誤的來源:
class User < ApplicationRecord
has_one :dob, dependent: :nullify
has_one :id, class_name: "Id", dependent: :nullify
...
end
我已經嘗試使用 class_name 但它不起作用,有沒有辦法避免它?還是我應該更改型號名稱?
uj5u.com熱心網友回復:
想象一下以下情況:您打開一個 Rails 控制臺并輸入:
User.last.id
現在rails不知道,你想要什么。有兩種選擇:
- 回傳用戶表id列的值
- 回傳具有正確 user_id 的類 id 的記錄
簡而言之:您不能同時擁有兩者,需要從用戶模型中洗掉 id(不推薦)或重命名您的模型。在不知道模型應該做什么的情況下:id 作為名稱似乎是一個非常糟糕的選擇。嘗試更具描述性的內容。
如果您有興趣:有一個很好的保留字串列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/460263.html
