Rails after_initialize仅在"new"消息上初始化. [英] Rails after_initialize only on "new"

查看:49
本文介绍了Rails after_initialize仅在"new"消息上初始化.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下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中我拥有:

A sport can't exist without the product, so in my sports_controller.rb I had:

def new
  @sport = Sport.new
  @sport.product = Product.new
...
end

我尝试使用after_initialize将产品的创建移至运动模型:

I tried to move the creation of the product to the sport model, using after_initialize:

after_initialize :create_product

def create_product
 self.product = Product.new
end

我很快了解到,每当实例化模型时(即从find调用)就会调用after_initialize.所以那不是我想要的行为.

I quickly learned that after_initialize is called whenever a model is instantiated (i.e., from a find call). So that wasn't the behavior I was looking for.

我应该如何对所有sport都具有product的需求进行建模?

Whats the way I should be modeling the requirement that all sport have a product?

谢谢

推荐答案

将逻辑放入控制器中可能是最佳答案,但是您可以通过执行以下操作使after_initialize起作用:

Putting the logic in the controller could be the best answer as you stated, but you could get the after_initialize to work by doing the following:

after_initialize :add_product

def add_product
  self.product ||= Product.new
end

这样,仅当不存在产品时才设置产品.与在控制器中包含逻辑相比,这可能不值得花费开销和/或不够清晰.

That way, it only sets product if no product exists. It may not be worth the overhead and/or be less clear than having the logic in the controller.

编辑:根据Ryan的回答,从性能角度考虑,以下方法可能会更好:

Per Ryan's answer, performance-wise the following would likely be better:

after_initialize :add_product

def add_product
  self.product ||= Product.new if self.new_record?
end

这篇关于Rails after_initialize仅在"new"消息上初始化.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆