我有这个最小的示例模型:
class Book < ActiveRecord::Base
belongs_to :author
delegate :name, prefix: true, to: author
after_initialize { author ||= Author.new }
end
发布表单数据后,我的框架(是的,ActiveAdmin)执行此操作:Book.new {author_name: 'Some Dude'}
导致author_name
未被写入,因为after_initialize
回调仅在{{1}初始化后调用}}。
我怎样才能建立关联&#34;之前&#34;或&#34;而&#34;初始化?任何好的模式?
答案 0 :(得分:2)
您可以覆盖initialize方法并调用super:
class Book < ActiveRecord::Base
belongs_to :author
delegate :name, prefix: true, to: author
def initialize(*args)
author ||= Author.new
super
end
end