如果记录中有任何更改,请运行一个函数

问题描述 投票:0回答:3

我正在尝试从请求模型创建遇到记录。我想要的是after_update:create_encounter只有在我尝试创建的请求记录中有任何更改时才会工作:before_update:check_changes但是我无法弄清楚check_changes函数如何实现以查看是否有任何更改请求记录中的更改。请帮忙

record.rb

class Request < ApplicationRecord
  after_create :create_encounter
  before_update :check_changes
  after_update :create_encounter

  has_many :encounters, dependent: :destroy

  def create_encounter
    hello = Encounter.new
    hello.request_id = self.id
    hello.status_change_date = DateTime.now.to_date
    hello.notes = self.notes
    hello.save
  end

 def check_changes

 end

end

请求的架构

create_table "requests", force: :cascade do |t|

    t.string "applicant_name"
    t.string "pickup_location"
    t.string "notes"

end

加成

def create_encounter
    if self.changed?
       hello = Encounter.new
       hello.request_id = self.id
       hello.status_change_date = DateTime.now.to_date
       hello.notes = self.notes
       hello.save
    end
  end
ruby-on-rails ruby-on-rails-5
3个回答
1
投票

您可以使用来自saved_changes?()ActiveRecord::AttributeMethods::Dirty,它将告诉您最后一次调用save是否包含任何更改。


1
投票

你必须调用:create_encounter before_save。


0
投票
class Request < ApplicationRecord
  before_save :create_encounter
  after_create :create_encounters
  belongs_to :clinic
  belongs_to :client
  has_many :encounters, dependent: :destroy

  def create_encounter
    if self.changed?()
      hello = Encounter.new
      hello.request_id = self.id
      hello.admin_id = current_admin_id
      hello.status_change_date = DateTime.now.to_date
      hello.notes = self.notes
      hello.save
    end
  end

  def create_encounters
    hello = Encounter.new
    hello.request_id = self.id
    hello.admin_id = current_admin_id
    hello.status_change_date = DateTime.now.to_date
    hello.notes = self.notes
    hello.save
  end  

  def current_admin_id
    Admin.current_admin.try(:id)
  end

end
© www.soinside.com 2019 - 2024. All rights reserved.