在初始化时建立关联以满足代表

Build association while initializing to satisfy delegates

我有这个最小的示例模型:

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 回调仅在 Book

如何建立关联 "before" 或 "while" 初始化?有什么好的模式吗?

您可以覆盖初始化方法并调用 super:

class Book < ActiveRecord::Base
  belongs_to :author
  delegate :name, prefix: true, to: author

  def initialize(*args)
     author ||= Author.new
     super 
  end 
end