MechDog MechDog - 6 months ago 12
Ruby Question

How do you prevent the saving of a nested object but still save the main object?

I have a 'notes' object nested inside multiple other objects, for example 'user'. I want to only add/save a new note if someone has filled out something in the note_text field. I thought I found a way but it stops the saving of the rest of the object as well due to the error.

class User < ActiveRecord::Base
has_many :notes

accepts_nested_attributes_for :notes

end

class Note < ActiveRecord::Base
belongs_to :user

before_save :check_for_blank_note

def check_for_blank_note
if self.note_text.nil? || self.note_text.blank?
false
else
true
end
end
end


I was hoping to just stop the save on the notes and let the user be updated and saved.

Answer

Use :reject_if to silently drop any record that does not pass your logic:

class User < ActiveRecord::Base
  has_many :notes
  accepts_nested_attributes_for :notes, reject_if: proc { |attributes| attributes['note_text'].blank? }
end
Comments