{"id":850,"date":"2014-01-10T22:26:10","date_gmt":"2014-01-10T16:56:10","guid":{"rendered":"http:\/\/www.allerin.com\/blog\/?p=850"},"modified":"2014-01-17T12:38:47","modified_gmt":"2014-01-17T07:08:47","slug":"save-an-object-skipping-callbacks-in-rails-3-application","status":"publish","type":"post","link":"https:\/\/www.allerin.com\/blog\/save-an-object-skipping-callbacks-in-rails-3-application\/","title":{"rendered":"SAVE AN OBJECT SKIPPING CALLBACKS IN RAILS 3 APPLICATION"},"content":{"rendered":"<p>Many times, we need to skip validation as well as callbacks while saving the object, due to the requirement of a Ruby on Rails application. In Rails 3.x, to skip validation we can use (:validate =&gt; false) and to skip callbacks we tend to use ActiveSupport::Callbacks::ClassMethods#skip_callback (http:\/\/apidock.com\/rails\/ActiveSupport\/Callbacks\/ClassMethods\/skip_callback).<\/p>\n<p style=\"text-align: left;\">ActiveSupport::Callbacks::ClassMethods#skip_callback<\/p>\n<p style=\"text-align: left;\">This method can get us into trouble, as it is not thread-safe. So to skip callbacks, there is no option as (:callbacks =&gt; false) or (:skip_callbacks =&gt; true) . In order to achieve similar functionality of skipping callbacks following gems\/code snippets are widely referred:<\/p>\n<ol>\n<li>gem &#8216;skip_activerecord_callbacks&#8217;\u00a0(https:\/\/github.com\/dball\/skip_activerecord_callbacks)<\/li>\n<li>Blog:Disabling ActiveModel callbacks\u00a0(http:\/\/jeffkreeftmeijer.com\/2010\/disabling-activemodel-callbacks\/)<\/li>\n<li>Activate\/deactivate callbacks snippet\u00a0(https:\/\/gist.github.com\/Tei\/670283)<\/li>\n<li>Providing (:callbacks =&gt; false) option\u00a0(https:\/\/github.com\/rails\/rails\/pull\/4885,\u00a0Commit: https:\/\/github.com\/patrick99e99\/rails\/commit\/d7787d7220a8935d5ee3765824ef0c138b51a4f5)<\/li>\n<li>gem &#8216;sneaky-save&#8217;\u00a0(https:\/\/github.com\/partyearth\/sneaky-save)<\/li>\n<\/ol>\n<p style=\"text-align: left;\">Since I have been working with Rails for quite some time now, and been observing this situation quite frequently. Based on my observations, I tend to conclude the following on above references and methods,<\/p>\n<ol>\n<li>gem &#8216;skip_activerecord_callbacks&#8217; : Class Methods are provided which functions similar to *_without_callbacks methods(form Rails 2.x)<\/li>\n<li>Blog:Disabling ActiveModel callbacks : Method given sets skipped callbacks after the necessary work is done but again this is using skip_callback method<\/li>\n<li>Activate\/deactivate callbacks snippet : These are also class methods which are removing callbacks definitions<\/li>\n<li>Providing (:callbacks =&gt; false) option : This a decent option and also provides same format as (:validate =&gt; false) but due to a large number of changes in core rails part it is very difficult to use in application.<\/li>\n<li>gem &#8216;sneaky-save&#8217; : This is quite a simple solution. It generates raw SQL query to save the record. Hence, no callbacks or validations are triggered. Out of above mentioned references gem &#8216;sneaky-save&#8217; found to be meeting the requirement of the Ruby on Rails Application. This gem skips all validation as well as all callbacks.<\/li>\n<\/ol>\n<p>INSTALLATION<\/p>\n<pre>$ gem install sneaky-save<\/pre>\n<p style=\"text-align: left;\">Now add it to your Gemfile with:<\/p>\n<pre>gem 'sneaky-save'<\/pre>\n<p style=\"text-align: left;\">Run the bundle command to install it.<\/p>\n<p style=\"text-align: left;\">Once you install sneaky-save and add it to your Gemfile, you are ready to use it in your application.<\/p>\n<p style=\"text-align: left;\">USAGE<\/p>\n<pre># Create\r\n\r\n@user = User.new\r\n@user.first_name = 'UserFirstName'\r\n@user.last_name = 'UserLastName'\r\n@user.sneaky_save\r\n\r\n# Update\r\n\r\n@user = User.find(123) # say record id = 123 \r\n@user.first_name = 'NewUserFirstName'\r\n@user.last_name = 'NewUserLastName'\r\n@user.sneaky_save<\/pre>\n<p style=\"text-align: left;\">LOGIC<\/p>\n<p style=\"text-align: left;\">All the logic is in SneakySave module (https:\/\/github.com\/partyearth\/sneaky-save\/blob\/master\/lib\/sneaky-save.rb)<\/p>\n<pre>def sneaky_save\r\n  begin\r\n    # If it is a new record then create a new record else update changed attributes\r\n    new_record? ? sneaky_create : sneaky_update\r\n  rescue ActiveRecord::StatementInvalid\r\n    false\r\n  end\r\nend<\/pre>\n<p style=\"text-align: left;\">We can use sneaky_save on new or existing object. Depending on the object, if it is a new object then to create object sneaky_create is used to generate SQL insert query. If the object is an existing object then SQL update query is generated.<\/p>\n<p style=\"text-align: left;\"># File https:\/\/github.com\/partyearth\/sneaky-save\/blob\/master\/lib\/sneaky-save.rb, line 26<\/p>\n<pre>def sneaky_create\r\n\r\n  if self.id.nil? &amp;&amp; connection.prefetch_primary_key?(self.class.table_name) \r\n    self.id = connection.next_sequence_value(self.class.sequence_name) \r\n  end\r\n\r\n  attributes_values = send :arel_attributes_values\r\n\r\n  # Remove the id field for databases like Postgres which will raise an error on id being NULL \r\n  if self.id.nil? &amp;&amp; !connection.prefetch_primary_key?(self.class.table_name) \r\n    attributes_values.reject! { |key,_| key.name == 'id' }\r\n  end\r\n\r\n  # Uses ActiveRecord's insert() method to generate insert SQL query \r\n  new_id = if attributes_values.empty?\r\n    self.class.unscoped.insert connection.empty_insert_statement_value \r\n  else\r\n    self.class.unscoped.insert attributes_values\r\n  end\r\n\r\n  @new_record = false\r\n  !!(self.id ||= new_id)\r\n\r\nend<\/pre>\n<p style=\"text-align: left;\">Here the main functioning is done by Model.insert(). It is ActiveRecord::ConnectionAdapters::DatabaseStatements#insert method that generates SQL insert query for creating a new record.<\/p>\n<p style=\"text-align: left;\"># File https:\/\/github.com\/partyearth\/sneaky-save\/blob\/master\/lib\/sneaky-save.rb, line 50<\/p>\n<pre>def sneaky_update\r\n  # Handle no changes.\r\n  return true if changes.empty?\r\n  # Here we have changes --&gt; save them.\r\n  pk = self.class.primary_key\r\n  original_id = changed_attributes.has_key?(pk) ? changes[pk].first : send(pk) \r\n  !self.class.update_all(attributes, pk =&gt; original_id).zero?\r\nend<\/pre>\n<p style=\"text-align: left;\">Here Model.update_all() is called for generating SQL update query and update the given record. These methods are called from ActiveRecord::Base#update_all<\/p>\n<p style=\"text-align: left;\">HOW IT WORKS?<\/p>\n<p style=\"text-align: left;\">&#8216;sneaky_save&#8217; method internally calls &#8216;sneaky_create&#8217; and &#8216;sneaky_update&#8217; as per object state. In &#8216;sneaky_create&#8217; method, INSERT SQL query is generated and executed. Direct INSERT SQL is executed without involving Model, thus no validation or callback is triggered. In &#8216;sneaky_update&#8217; method, UPDATE SQL query are generated and executed to manipulate database. Here it does not instantiate Model object, hence does not trigger any validation or callback.<\/p>\n<p>ADVANTAGE<\/p>\n<p style=\"text-align: left;\">Following existing methods which are available for an update but with their own limitations.<\/p>\n<p style=\"text-align: left;\">update_attributes : Validation is invoked. Callbacks are invoked.<\/p>\n<p style=\"text-align: left;\">update_attribute : Validation is skipped. Callbacks are invoked.<\/p>\n<p style=\"text-align: left;\">update_column : Validation is skipped. Callbacks are skipped.<\/p>\n<p style=\"text-align: left;\">update_columns : Validation is skipped. Callbacks are skipped. (available in Rails4)<\/p>\n<p style=\"text-align: left;\">update_all : Validation is skipped. Callbacks are skipped.<\/p>\n<p style=\"text-align: left;\">sneaky_save: sneaky-save is easy to use and have clean syntax. It can be called directly on the object without passing any parameters to it.<\/p>\n<p style=\"text-align: left;\">DRAWBACKS: Does not reload updated record by default. Does not save associated collections. Saves only belongs_to relations. All the callbacks are skipped, does not have any option to trigger\/skip selected callbacks<\/p>\n<p style=\"text-align: left;\">These are mostly my observations so pros and cons may not be limited to what I have posted above \ud83d\ude42 . I am willing to learn the feedback of other community guys, &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In a Ruby on Rails application, we need to skip validation as well as callbacks while saving the object.<br \/>\nIn Rails 3.x, commonly used method to skip callbacks is ActiveSupport&#8217;s skip_callback method, but this method could cause problems as its not thread-safe. This post talks about alternative way to achieve the purpose.<\/p>\n","protected":false},"author":9192191,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":"","_links_to":"","_links_to_target":""},"categories":[3],"tags":[14,20,98],"class_list":["post-850","post","type-post","status-publish","format-standard","hentry","category-technology","tag-rails-3","tag-ruby-on-rails","tag-skip-callback"],"_links":{"self":[{"href":"https:\/\/www.allerin.com\/blog\/wp-json\/wp\/v2\/posts\/850","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.allerin.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.allerin.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.allerin.com\/blog\/wp-json\/wp\/v2\/users\/9192191"}],"replies":[{"embeddable":true,"href":"https:\/\/www.allerin.com\/blog\/wp-json\/wp\/v2\/comments?post=850"}],"version-history":[{"count":9,"href":"https:\/\/www.allerin.com\/blog\/wp-json\/wp\/v2\/posts\/850\/revisions"}],"predecessor-version":[{"id":913,"href":"https:\/\/www.allerin.com\/blog\/wp-json\/wp\/v2\/posts\/850\/revisions\/913"}],"wp:attachment":[{"href":"https:\/\/www.allerin.com\/blog\/wp-json\/wp\/v2\/media?parent=850"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.allerin.com\/blog\/wp-json\/wp\/v2\/categories?post=850"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.allerin.com\/blog\/wp-json\/wp\/v2\/tags?post=850"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}