Rails 4: How to cancel save on a "before_save" callback?

ruby-on-rails

Solution

To prevent record from being saved, you should simply return `false`:

def check_for_similar_record
  if ProductsColor.exists?(color_id: self.color_id, product_id: self.product_id)
    # merge values
    false
  else
    true
  end
end

Problem

I have complicated models / forms. I don't want repeated records, so I want to merge records that have similar attributes. How would I cancel "save" using a before_save callback? This is what I'm thinking: ``` class ProductsColor < ActiveRecord::Base before_save :check_for_similar_record def check_for_similar_record if ProductsColor.exist?(color_id: self.color_id, product_id: self.product_id) # merge values with existing ProductsColor and stop self from saving end end end ```

Original source

Related problems