【问题标题】:How can you override the activerecord has_many assoication build method?如何覆盖 activerecord has_many 关联构建方法?
【发布时间】:2026-01-27 15:20:03
【问题描述】:

我想重写 has_many 关联的构建方法。

class OtherThings < ActiveRecord::Base
  belongs_to :my_model
end

class MyModel < ActiveRecord::Base
  has_many :other_things
end

这样

m = MyModel.create
m.other_things.build  # i'd like to add additional logic within the build method...

我已经更新了 OtherThings 的新方法,但这有点混乱。我希望我的逻辑仅在关联时发生,因此构建...

【问题讨论】:

    标签: ruby-on-rails activerecord associations


    【解决方案1】:

    我不确定你想用 build 做什么。如果您尝试添加更多方法,只需将 .whatever_method 附加到末尾。此外,模型将始终关联。

    【讨论】:

      【解决方案2】:

      我能够通过使用 around_create 解决我的问题。

      【讨论】: