初始化时构建关联以满足代理

时间:2015-02-13 10:12:20

标签: ruby-on-rails activerecord delegates associations activeadmin

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

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;初始化?任何好的模式?

1 个答案:

答案 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