2017-12-30 16 views
0

AR 콜백 (after_save)을 사용하여 최신 '업데이트'또는 '작성'에 연결이 추가되었는지 확인하려고합니다. 그러나, 나는 그것을 할 올바른 방법을 찾을 수없는 것 같습니다. 여기 'create'및 'update'에 대한 추가 연결 확인 - 활성 레코드

class Submission < ActiveRecord 
    has_many :notes, inverse_of: :submission, dependent: :destroy 
    accepts_nested_attributes_for :notes, :reject_if => proc { |attributes| attributes['message'].blank? }, allow_destroy: true 
end 

내가 새 메모 테이블 업데이트시 추가되거나 생성 된 경우,보고 싶은 그 방법 내 after_save

after_save :build_conversation 

...이 논리가하는

def build_conversation 
    if self.notes.any? 
    binding.pry 
    end 
end 

입니다 메모가 존재할 수 있다면 괜찮습니다. 그럼에도 불구하고 업데이트에 새로운 메모가 추가되거나 작성되는 경우에만이 블록에 들어가기를 원합니다 ...

답변

1

체크 아웃 this post을 확인하십시오. 기본적으로 include ActiveModel::Dirty을 모델에 추가 한 다음 after_change 콜백에 if_notes_changed을 확인합니다. 이 방법은 method_missing을 사용하여 정의됩니다. 예를 들어 name 열이있는 경우 if_name_changed 등을 사용할 수 있습니다. 이전 값과 새 값을 비교해야하는 경우 previous_changes을 사용할 수 있습니다.

양자 택일로, 당신은과 같이 around_save를 사용할 수 있습니다

around_save :build_conversation 

def build_conversation 
    old_notes = notes.to_a # the self in self.notes is unnecessary 
    yield # important - runs the save 
    new_notes = notes.to_a 
    # binding.pry 
end 
관련 문제