[英]has_many Using class Versus class_name
I've been modelling some custom has_many
associations like this: 我一直在建模一些自定义的
has_many
关联,如下所示:
has_many :friends, class: User
I recently found that this style isn't documented and the API docs: 我最近发现该样式未记录下来,并且API文档:
has_many :friends, class_name: 'User'
I haven't noticed any problems with the former syntax, and I'm curious why the later syntax is used (wouldn't it be better to avoid converting the string to a class?). 我没有注意到前一种语法有任何问题,并且很好奇为什么要使用后一种语法(避免将字符串转换为类会更好吗?)。 Any reason to switch from the former to the later?
有什么理由从前者切换到后者?
Well in coming version of rails class
has been renamed to anonymous_class
. 那么在未来的轨道版本
class
已更名为anonymous_class
。 Although it is still in the master branch. 尽管它仍然在master分支中。 There is a problem with the use of
:class
and here it goes from the commit : :class
的使用存在问题,这是从commit出发的:
In 1f006c an option was added called :class to allow passing anonymous classes to association definitions.
在1f006c中,添加了一个名为:class的选项,以允许将匿名类传递给关联定义。 Since using :class instead of :class_name is a fairly common typo even amongst experienced developers this can result in hard to debug errors arising in raise_on_type_mismatch?
因为即使在有经验的开发人员中,使用:class而不是:class_name也是很常见的错字,这会导致在debug_on_type_mismatch中引起的难以调试的错误吗?
To fix this we're renaming the option from :class to :anonymous_class as that is a more correct description of what the option is for.
为了解决这个问题,我们将选项从:class重命名为:anonymous_class,因为这是对该选项的正确描述。 Since this was an internal, undocumented option there is no need for a deprecation.
由于这是内部未记录的选项,因此无需弃用。
It is in 4-2-stable 4-2稳定
Rename
:class
to:anonymous_class
in association options.在关联选项中将
:class
重命名为:anonymous_class
。 Fixes #19659修复#19659
If you needed to define a class dynamically or run a method that would return a class then the first option would be useful. 如果您需要动态定义一个类或运行将返回一个类的方法,则第一个选项将很有用。
Honestly though I can't think of a good scenario in which that would be an ideal approach. 老实说,尽管我无法想到一个理想的方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.