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

拟墨画扇 提交于 2019-12-23 09:34:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!