【问题标题】:Build association while initializing to satisfy delegates在初始化时建立关联以满足委托
【发布时间】:2015-02-13 10:12:19
【问题描述】:

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

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 初始化后调用。

如何在初始化“之前”或“期间”建立关联?有什么好的图案吗?

【问题讨论】:

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


    【解决方案1】:

    你可以重写initialize方法并调用super:

    class Book < ActiveRecord::Base
      belongs_to :author
      delegate :name, prefix: true, to: author
    
      def initialize(*args)
         author ||= Author.new
         super 
      end 
    end
    

    【讨论】:

    • 听起来不错,这可能是唯一可行的解​​决方案。但是在谷歌搜索时,我发现不鼓励覆盖 initialize,因为 ActiveRecord 有时不会以标准方式初始化对象。
    • 你没有覆盖它,因为你称之为超级。这意味着你正在做某事,然后说,去做你想做的事
    • 是的,但initialize 在某些情况下可能不会被调用,这是我所读到的。
    • 从技术上讲,您可以覆盖 new,而不是初始化,这会做同样的事情。不过要小心,并测试您的代码...
    • 我指的是这篇文章:blog.dalethatcher.com/2008/03/… -- 从那以后我没有检查过 AR 是否发生了变化。它可能有,对于我的用例,我认为你的解决方案应该没问题。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 2012-08-26
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多