ActiveRecord: pass class instead of string to class_name when defining associations

Are there any consequences or gotchas for passing in a class instead of a string when defining an association?

belongs_to :owner, class_name: User 

Unlike:

 belongs_to :owner, class_name: "User" 
+6
source share
2 answers

The class may not load, but in this case you will get NameError: uninitialized constant User .

You should use "User" for this reason, as implied by the option name :class_name , not :class .

+12
source

In rare cases, I encounter some random errors when using classes (User) instead of the class name as a string ("User"). I cannot reproduce them and solve this by simply restarting the application server.

It can be a symbol. It cannot be a class constant, because if you have two connected models, when the first loads, the second is not defined yet, so the constant will not be defined, and this will lead to an error.

Source: https://github.com/rails/rails/issues/6486

0
source

Source: https://habr.com/ru/post/959359/


All Articles