【发布时间】:2012-03-07 22:42:55
【问题描述】:
我有以下 2 个模型
class Sport < ActiveRecord::Base
has_many :charts, order: "sortWeight ASC"
has_one :product, :as => :productable
accepts_nested_attributes_for :product, :allow_destroy => true
end
class Product < ActiveRecord::Base
belongs_to :category
belongs_to :productable, :polymorphic => true
end
没有产品就不可能有运动,所以在我的sports_controller.rb 中我有:
def new
@sport = Sport.new
@sport.product = Product.new
...
end
我尝试将产品的创建转移到运动模型,使用after_initialize:
after_initialize :create_product
def create_product
self.product = Product.new
end
我很快了解到,只要实例化模型(即通过 find 调用),就会调用 after_initialize。所以这不是我想要的行为。
我应该如何建模所有sport 都有product 的要求?
谢谢
【问题讨论】:
标签: ruby-on-rails model nested-attributes