"You tried to define an association named id on the model x" 在 Rails
"You tried to define an association named id on the model x" in Rails
我有一个模型名称 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 但它不起作用,有没有办法避免它?或者我应该更改型号名称?
想象以下情况:您打开 rails 控制台并输入:
User.last.id
现在rails不知道,你想要什么。有两种选择:
- Return用户id列的值table
- Return class id 正确的记录 user_id
简而言之:您不能同时拥有两者,需要从用户模型中删除 ID(不推荐)或重命名您的模型。在不知道模型应该做什么的情况下:id 作为名称似乎是一个非常糟糕的选择。尝试更具描述性的内容。
如果你有兴趣:有一个不错的list of reserved words。
我有一个模型名称 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 但它不起作用,有没有办法避免它?或者我应该更改型号名称?
想象以下情况:您打开 rails 控制台并输入:
User.last.id
现在rails不知道,你想要什么。有两种选择:
- Return用户id列的值table
- Return class id 正确的记录 user_id
简而言之:您不能同时拥有两者,需要从用户模型中删除 ID(不推荐)或重命名您的模型。在不知道模型应该做什么的情况下:id 作为名称似乎是一个非常糟糕的选择。尝试更具描述性的内容。
如果你有兴趣:有一个不错的list of reserved words。