Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
713 views
in Technique[技术] by (71.8m points)

Rails before_update callback with nested attributes

I have two models (lets call then A and B).

A has_many bs and B belongs_to 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

Other than that, B has a before_update callback that sets some_field to nil if A has some_enum_value set.

Since this relation is used on a nested form, that before_update from B is only being called if I update a attribute form B. If I only change a value form A that callback is not called.

How can I call B's before_update when A is updated?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For belongs to associations you can use the touch option:

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

Which would update a.updated_at when you update B. However this option does not exist for has_many relations since it could have potentially disastrous performance consequences (If an A has 1000s or more Bs).

You can roll your own however:

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
  after_update :cascade_update!

  def cascade_update!
    # http://api.rubyonrails.org/classes/ActiveRecord/Batches.html#method-i-find_each
    bs.find_each(batch_size: 100) do |b|
      b.update!(updated_at: Time.zone.now)
    end
  end
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...