Rails 3 skip validations and callbacks

Ruby on-RailsRuby on-Rails-3Activerecord

Ruby on-Rails Problem Overview


I have a particularly complex model with validations and callbacks defined. The business needs now calls for a particular scenario where adding a new record requires skipping the validations and callbacks. What's the best way to do this?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

This works in Rails 3:

Model.skip_callback(:create)
model.save(:validate => false)
Model.set_callback(:create)

(API docs and related question)

Solution 2 - Ruby on-Rails

Use ActiveRecord::Persistence#update_column, like this:

Model.update_column(field, value)

Solution 3 - Ruby on-Rails

If the goal is to simply insert or update a record without callbacks or validations, and you would like to do it without resorting to additional gems, adding conditional checks, using RAW SQL, or futzing with your exiting code in any way, it may be possible to use a "shadow object" which points to your existing db table. Like so:

class ImportedUser < ActiveRecord::Base
  # To import users with no validations or callbacks
  self.table_name = 'users'
end

This works with every version of Rails, is threadsafe, and completely eliminates all validations and callbacks with no modifications to your existing code. Just remember to use your new class to insert the object, like:

ImportedUser.new( person_attributes )

Solution 4 - Ruby on-Rails

My take was like this (note: this disables callbacks on create, for update, delete and others you need to add them to array).

    begin
      [:create, :save].each{|a| self.class.skip_callback(a) } # We disable callbacks on save and create
      
      # create new record here without callbacks, tou can also disable validations with 
      # .save(:validate => false)
    ensure
      [:create, :save].each{|a| self.class.set_callback(a) }  # and we ensure that callbacks are restored
    end

Solution 5 - Ruby on-Rails

I would recommend NOT using the skip_callback approach since it is not thread safe. The sneaky save gem however is since it just runs straight sql. Note this will not trigger validations so you will have to call them yourself (ex: my_model.valid?).

Here are some samples from their docs:

# Update. Returns true on success, false otherwise.
existing_record.sneaky_save

# Insert. Returns true on success, false otherwise.
Model.new.sneaky_save

# Raise exception on failure.
record.sneaky_save!

Solution 6 - Ruby on-Rails

What about adding a method to your model that let's you skip the callbacks?

class Foo < ActiveRecord::Base
  after_save :do_stuff

  def super_secret_create(attrs)
    self.skip_callback(:create)
    self.update_attributes(attrs)
    self.save(:validate => false)
    self.set_callback(:create)
  end
end
    

If you end up using something like this, I would recommend using self in the method instead of the model name to avoid connascence of name.

I also ran across a gist from Sven Fuchs that looks nice, it's here

Solution 7 - Ruby on-Rails

I wrote a simple gem for skipping validations adhoc, but it could probably be updated to include skipping call backs as well.

https://github.com/npearson72/validation_skipper

You could take the can_skip_validation_for in the gem and add functionality for also skipping callbacks. Maybe call the method can_skip_validation_and_callbacks_for

Everything else would work the same. If you want help with doing that, let me know.

Solution 8 - Ruby on-Rails

This hack worked for me at last (redefined _notify_comment_observer_for_after_create method for the object):

if no_after_create_callback
  def object._notify_comment_observer_for_after_create; nil; end
end

Solution 9 - Ruby on-Rails

None of these will work if your validations are written into the database itself.

+------------------------------------+--------------------------------------------------+------+-----+--------------------+----------------+
| Field                              | Type                                             | Null | Key | Default            | Extra          |
+------------------------------------+--------------------------------------------------+------+-----+--------------------+----------------+
| status                             | enum('Big','Small','Ugly','Stupid','Apologetic') | NO   |     | Stupid             |                |

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnny KlassyView Question on Stackoverflow
Solution 1 - Ruby on-RailsDinatihView Answer on Stackoverflow
Solution 2 - Ruby on-RailsbowserseniorView Answer on Stackoverflow
Solution 3 - Ruby on-RailsBrad WerthView Answer on Stackoverflow
Solution 4 - Ruby on-RailsMarcin RaczkowskiView Answer on Stackoverflow
Solution 5 - Ruby on-RailsEricView Answer on Stackoverflow
Solution 6 - Ruby on-RailsCaley WoodsView Answer on Stackoverflow
Solution 7 - Ruby on-RailsNathanView Answer on Stackoverflow
Solution 8 - Ruby on-RailsTuteCView Answer on Stackoverflow
Solution 9 - Ruby on-RailsJoshua CookView Answer on Stackoverflow