ruby 检测关联模型中的更改

2ekbmq32  于 5个月前  发布在  Ruby
关注(0)|答案(1)|浏览(63)

我在ruby on rails项目中有一个lead model。它与lead_type model相关联。lead model中有一个分数,该分数是根据lead_type model中存在的serving_factor计算的。如果serving_factor的值发生变化,则需要更新lead model中存在的分数。lead model中是否有任何方法可以做到这一点。Lms::Lead:

belongs_to :lead_type, class_name: "Lms::LeadType", optional: true

字符串
前面的实现是通过在LeadType模型中编写作业来完成的。如果有更改,则运行作业以更新Lead中的分数。

gfttwv5a

gfttwv5a1#

您可以像这样使用Rails回调和委托方法,例如,您的文件位于app/models/lms/lead_type.rb

# app/models/lms/lead_type.rb
class Lms::LeadType < ApplicationRecord
  has_many :leads, class_name: "Lms::Lead"

  after_update :update_lead_scores, if: :serving_factor_changed?

  private

  def update_lead_scores
    leads.each do |lead|
      lead.update_score_based_on_serving_factor
    end
  end
end

# app/models/lms/lead.rb
class Lms::Lead < ApplicationRecord
  belongs_to :lead_type, class_name: "Lms::LeadType", optional: true

  delegate :serving_factor, to: :lead_type, allow_nil: true

  def update_score_based_on_serving_factor
    # logic to calculate and update score based on serving_factor
    self.score = calculate_new_score
    save
  end

  private

  def calculate_new_score
    # Your logic to calculate the score based on serving_factor
  end
end

字符串

相关问题