【问题标题】:Accessing before update value of active record object在活动记录对象的更新值之前访问
【发布时间】:2016-11-08 20:03:32
【问题描述】:

我已经实现了一个在成功更新活动记录对象时调用的函数,但是我必须将活动记录值的更新前后值传递给该函数。我正在尝试通过以下方式实现,但是传递的值只是更新的值。

def update
 lead_before_update = @old_car_lead

 respond_to do |format|
  if @old_car_lead.update(old_car_lead_params)
    format.html { redirect_to @old_car_lead, notice: 'Lead was successfully updated.' }
    format.json { render :show, status: :ok, location: @old_car_lead }
    lead_after_update = @old_car_lead

    Lead.send_lead(lead_before_update, lead_after_update)

  else
    format.html { render :edit }
    format.json { render json: @old_car_lead.errors, status: :unprocessable_entity }
  end
end

结束

当我尝试记录lead_before_update 和lead_after_update 的值时,我发现两者的值相同。

谁能告诉我如何将更新前和更新后的值传递给函数。

【问题讨论】:

  • 使用lead_before_update = @old_car_lead.dup
  • 就像一个魅力。谢谢你:)

标签: ruby-on-rails activerecord rails-activerecord


【解决方案1】:

lead_before_updatelead_after_update 都指向同一个对象(old_car_lead)。当它改变时,它改变了一切。

这里有两种方式:

  1. 您应该复制该对象并分配给一个变量。

    lead_before_update = @old_car_lead.dup lead_after_update = @old_car_lead.dup

  2. 你可以使用@old_car_lead.attribute_name_was它会给你attribute_name之前的值

第二个选项的参考:What is the ActiveModel method attribute "_was" used for?

【讨论】:

    猜你喜欢
    • 2021-10-13
    • 2018-05-31
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多