Search code examples
ruby-on-rails-3model-associations

Can a one to many relationship in rails create a parent object?


If I have an category class that has many products and each product would only have one category so that my models looked like this:

class Product < ActiveRecord::Base
 belongs_to :category
end

and this:

class Category < ActiveRecord::Base
  has_many :products
end

Then, from the belongs_to side of products, can I create a category_name in my Product Model using: create_category? How can I tell what auto-generated methods are available to me on the product side of things?


Solution

  • How can I tell what auto-generated methods are available to me on the product side of things?

    By reading the corresponding documentation on api.rubyonrails.org (i.e. has_many and belongs_to). It tells you what methods are added.

    In your case, you get my_product.create_category and my_category.products.create along many other methods.