Search code examples
ruby-on-railsruby-on-rails-4belongs-to

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"

Why is that? Thanks!


Solution

  • The latter example does not work because there is no class called product_category. You are providing the wrong class name. Class names in Ruby should be written in CamelCase. When Rails looks for a product_category class it's not going to find it.

    Your first example works because Rails infers the name of the class from the name of the relationship.

    belongs_to :product_category, :foreign_key => :category_id
    

    It converts product_category to 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. The class_name argument should be used when the class name can not be inferred from the relationship name.