Ruby on rails 在批量分配初始化之前设置activerecord模型默认值

Ruby on rails 在批量分配初始化之前设置activerecord模型默认值,ruby-on-rails,activerecord,callback,mass-assignment,Ruby On Rails,Activerecord,Callback,Mass Assignment,我需要在对象从ModelAController\new传递到视图之前设置ModelA中的默认值(来自远程服务)。我在初始化后使用了。但是,在#create中,我遇到了一个问题。如果我使用model\u b.create\u model\u a(一些属性),则在初始化期间传入属性,然后在初始化之后被覆盖调用: class ModelA < ActiveRecord::Base after_initialize :set_defaults, if: :new_record? def

我需要在对象从
ModelAController\new
传递到视图之前设置
ModelA
中的默认值(来自远程服务)。我在初始化后使用了
。但是,在
#create
中,我遇到了一个问题。如果我使用
model\u b.create\u model\u a(一些属性)
,则在初始化期间传入属性,然后在初始化之后被
覆盖调用:

class ModelA < ActiveRecord::Base
  after_initialize :set_defaults, if: :new_record?

  def set_defaults
    self.c = "default"
    #actually a remote call, not something can be set as database default
  end
end

class ModelB < ActiveRecord::Base
  belongs_to :model_a
end

class ModelAController < ApplicationController
  #ModelA is nested under ModelB in routes.rb

  #GET /model_bs/:model_b_id/model_as/new
  def new
    model_b = ModelB.find(params[:model_b_id])
    #no problem
    respond_with model_b.build_model_a
  end

  #POST /model_bs/:model_b_id/model_as
  def create
    model_b = ModelB.find(params[:id])
    #problem:
    respond_with model_b.create_model_a({c: "not default"})
    #at this point the model_a instance still has attribute c set to "default"
  end
  ...
end

但是我觉得这使得Model的生命周期对于其他程序员来说有点像一个陷阱。这看起来是将最后两行重构为一行的一个明显的备选方案,但这会再次造成这个问题。是否有更整洁的解决方案?

进行条件赋值:

def set_defaults
  self.c ||= "default"
end
或者,在属性读取器中设置默认值,而不是在初始化钩子之后。这样,您只在实际需要属性值时设置默认值,因此,如果您不需要,它可以为您保存远程调用:

def c
  super || self.c = 'default'
end
def c
  super || self.c = 'default'
end