Ruby on rails 使用嵌套属性更新回调之前的Rails

Ruby on rails 使用嵌套属性更新回调之前的Rails,ruby-on-rails,callback,nested,nested-forms,nested-attributes,Ruby On Rails,Callback,Nested,Nested Forms,Nested Attributes,我有两种型号(让我们先调用A和B) A有许多bs和b属于A class A < ApplicationRecord has_many :bs, dependent: :destroy, inverse_of: :a accepts_nested_attributes_for :bs, reject_if: :all_blank, allow_destroy: true validates_associated :bs end class B < Application

我有两种型号(让我们先调用
A
B

A
有许多
b
s和
b
属于
A

class A < ApplicationRecord
  has_many :bs, dependent: :destroy, inverse_of: :a
  accepts_nested_attributes_for :bs, reject_if: :all_blank, allow_destroy: true
  validates_associated :bs
end


class B < ApplicationRecord
  belongs_to :a, inverse_of: :bs
  before_update :do_something, unless: Proc.new { |b| b.a.some_enum_value? if a }

  def do_something
    self.some_field = nil
  end

end
A类
除此之外,
B
有一个
before\u update
回调,如果
a
设置了
一些枚举值,则该回调将
一些字段设置为nil

由于此关系用于嵌套表单,因此仅当我更新属性表单
B
时才会调用
之前的
。如果我只更改值形式
a
,则不会调用该回调

更新
A
时,如何在更新之前调用
B


提前感谢。

对于属于关联,您可以使用
触摸
选项:

class B < ApplicationRecord
  belongs_to :a, inverse_of: :bs, touch: true
end

对于属于关联,您可以使用
触摸
选项:

class B < ApplicationRecord
  belongs_to :a, inverse_of: :bs, touch: true
end

从缩放的角度来看,在执行类似操作时,您需要非常小心。写操作很昂贵,通常你可以通过代理或使用连接来解决这个问题。非常感谢你,Max。我不明白这是如何回答这个问题的<如果我理解正确,代码>触摸在更新之前不会触发
。因此,它不会触发
do\u something
,从而将
some\u字段设置为
nil
@GProst,您完全正确。我编辑它是为了使用
.update
,它确实会触发回调。从缩放角度来看,在执行类似操作时,您需要非常小心。写操作很昂贵,通常你可以通过代理或使用连接来解决这个问题。非常感谢你,Max。我不明白这是如何回答这个问题的<如果我理解正确,代码>触摸在更新之前不会触发
。因此,它不会触发
do\u something
,从而将
some\u字段设置为
nil
@GProst,您完全正确。我将其编辑为使用
.update
,它会触发回调。