问题
Are there any implications or gotchas to passing in a class instead of a string when defining an association?
belongs_to :owner, class_name: User
As opposed to:
belongs_to :owner, class_name: "User"
回答1:
The class may not be loaded yet in which case you'll get a NameError: uninitialized constant User
.
You're supposed to use "User"
for this reason, as implied by the option name: :class_name
, not :class
.
回答2:
In rare case I encounter some random errors when using classes (User) instead of class name as a string ('User'). I am unable to reproduce them and solve this just by restarting app server.
It can be also a symbol. It cannot be a class constant because if you have two associated models, when the first is being loaded, the second is not yet defined, so the constant would not be defined, and this would give an error.
Source: https://github.com/rails/rails/issues/6486
来源:https://stackoverflow.com/questions/20390991/activerecord-pass-class-instead-of-string-to-class-name-when-defining-associati