ActiveRecord的:通过类,而不是字符串来定义关联时CLASS_NAME [英] ActiveRecord: Pass class instead of string to class_name when defining associations

查看:120
本文介绍了ActiveRecord的:通过类,而不是字符串来定义关联时CLASS_NAME的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何影响或陷阱界定关联时的一类传递一个字符串,而不是?

  belongs_to的:所有者,CLASS_NAME:用户

相对于

  belongs_to的:所有者,CLASS_NAME:用户


解决方案

类可能尚未加载在这种情况下,你会得到一个 NameError:未初始化的常数用户

你应该使用用户因为这个原因,作为隐含的选项名称::CLASS_NAME ,而不是:类

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"

解决方案

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.

这篇关于ActiveRecord的:通过类,而不是字符串来定义关联时CLASS_NAME的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆