MechDog
MechDog

Reputation: 548

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.

Upvotes: 0

Views: 420

Answers (2)

tadman
tadman

Reputation: 211560

You can always add a validation that precludes empty notes from being saved:

class Note < ActiveRecord::Base
  validates :note_text, presence: true
end

This will trigger an exception on saving if you use save! so you may want to screen out any invalid notes:

before_save :remove_empty_notes

def remove_empty_notes
  self.notes.reject! { |note| !note.valid? }
end

Upvotes: 1

Uzbekjon
Uzbekjon

Reputation: 11813

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

Upvotes: 4

Related Questions