Запустите функцию, если есть какие-либо изменения в записи - PullRequest
0 голосов
/ 01 апреля 2019

Я пытаюсь создать запись о столкновении из модели запроса.Я хочу, чтобы 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

Ответы [ 3 ]

1 голос
/ 01 апреля 2019

Вы должны вызвать: create_encounter before_save.

1 голос
/ 01 апреля 2019

Вы можете использовать saved_changes?() из ActiveRecord::AttributeMethods::Dirty, который сообщит вам, содержал ли последний вызов save какие-либо изменения.

0 голосов
/ 01 апреля 2019
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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...