Home > Enterprise >  "You tried to define an association named id on the model x" in Rails
"You tried to define an association named id on the model x" in Rails

Time:04-16

I have a model name id and I got this error: 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.)

Here is the source of the error:

class User < ApplicationRecord
  has_one :dob, dependent: :nullify
  has_one :id, class_name: "Id", dependent: :nullify
  ...
end

I already try to use class_name but it doesn't work, is there a way to avoit it? or should I change the model name?

CodePudding user response:

Imagine the following situation: You open a rails console and type in:

User.last.id

Now rails does not know, what you want. There are two options:

  1. Return the value of the id column of the user table
  2. Return the record of the class id with the correct user_id

In short: You can not have both and need to either remove the id from the user model (not recommended) or rename your model. Without knowing, what the model should do: id seems to be a very bad choice as a name. Try something more descriptive.

If you are interested: There is a nice list of reserved words.

  • Related