I have two models: Product
and Category
, which I want to tie together.
Say each product has a unique category, how do I set Rails to create (or generate) a new Category
object each time a user creates a new Product
object?
class Product < ActiveRecord::Base
after_create do
Category.create product: self
end
has_one :category
end
class Category < ActiveRecord::Base
belongs_to :product
end
and in console
> a= Product.create
> a.category
=> #<Category id: 1, product_id: 5, created_at: "2015-11-04 12:53:22", updated_at: "2015-11-04 12:53:22">