简体   繁体   English

Rails的问题归属于

[英]Issue with rails belongs_to

Hey guys just trying to figure out why this does not work. 大家只是想弄清楚为什么这行不通。 Basically this relationship does 基本上这种关系确实

belongs_to :product_category, :foreign_key => :category_id

And this one does not 而这个不

belongs_to :category, :class_name => :product_category, :foreign_key => :category_id

The error message is "NameError: uninitialized constant product::product_category" 错误消息是“ NameError:未初始化的常量product :: product_category”

Why is that? 这是为什么? Thanks! 谢谢!

The latter example does not work because there is no class called product_category . 后一个示例不起作用,因为没有名为product_category类。 You are providing the wrong class name. 您提供了错误的类名。 Class names in Ruby should be written in CamelCase. Ruby中的类名应使用CamelCase编写。 When Rails looks for a product_category class it's not going to find it. 当Rails寻找product_category类时,就不会找到它。

Your first example works because Rails infers the name of the class from the name of the relationship. 您的第一个示例之所以有效,是因为Rails从关系的名称中推断出类的名称。

belongs_to :product_category, :foreign_key => :category_id

It converts product_category to ProductCategory . 它将product_category转换为ProductCategory You can do the same thing yourself. 您可以自己做同样的事情。 Open up a terminal and type the following. 打开终端并输入以下内容。

'product_category'.camelize.constantize

You should pass in a string instead: 您应该改为输入一个字符串:

belongs_to :category, :class_name => 'ProductCategory', :foreign_key => :category_id

But in this case it would be redundant since Rails can already infer the class name. 但是在这种情况下,这将是多余的,因为Rails已经可以推断出类名。 The class_name argument should be used when the class name can not be inferred from the relationship name. 当无法从关系名称推断类名称时,应使用class_name参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM