Rails after_initialize 仅适用于“new" [英] Rails after_initialize only on "new"

查看:18
本文介绍了Rails after_initialize 仅适用于“new"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两种型号

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天全站免登陆