Skip to content

Instantly share code, notes, and snippets.

@jtsaito
Created January 9, 2015 14:44
Show Gist options
  • Save jtsaito/36f4437b0055a2146a8a to your computer and use it in GitHub Desktop.
Save jtsaito/36f4437b0055a2146a8a to your computer and use it in GitHub Desktop.
Note on backporting an ActiveRecord method from Rails 4.1 to Rails 2.3

This is a simple example for a backport of the ActiveRecord::Persistence#update_columns method which does not exists in Rails 2.3 but in Rails.

Create a ruby file config/iniitilizers/active_record_backport.rb and run a simple class_eval on the extended class, e.g. ActiveRecord::Persistence.

  ActiveRecord::Persistence.class_eval do

    # backport from Rails 4.1.0
    # see https://github.com/rails/rails/blob/4-1-stable/activerecord/lib/active_record/persistence.rb#L271
    def update_columns(attributes)
      raise ActiveRecordError, "cannot update on a new record object" unless persisted?

      attributes.each_key do |key|
        verify_readonly_attribute(key.to_s)
      end

      updated_count = self.class.unscoped.where(self.class.primary_key => id).update_all(attributes)

      attributes.each do |k, v|
        raw_write_attribute(k, v)
      end

      updated_count == 1
    end

    private

      def verify_readonly_attribute(name)
        raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name)
      end

  end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment