Skip to content

Instantly share code, notes, and snippets.

@mikelikesbikes
Last active January 24, 2017 00:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikelikesbikes/ae2f65ef03441e2daa4825637e668998 to your computer and use it in GitHub Desktop.
Save mikelikesbikes/ae2f65ef03441e2daa4825637e668998 to your computer and use it in GitHub Desktop.
Demonstrates a bug in ActiveRecord 5.0 where callbacks are not invoked as part of calling `update_attribute`
begin
require "bundler/inline"
rescue LoadError => e
$stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler"
raise e
end
gemfile(true) do
source "https://rubygems.org"
gem "rails", github: "rails/rails"
gem "arel", github: "rails/arel"
gem "sqlite3"
end
require "active_record"
require "minitest/autorun"
require "logger"
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :posts, force: true do |t|
t.string :slug
end
end
class Post < ActiveRecord::Base
before_save :update_slug
attr_accessor :new_slug
def update_slug
# this operation could be arbitratily complex, what's important
# is that after the method is called, the object's attributes will
# have changed as a result of the before_save, so it should be saved
self.slug = new_slug
end
end
class BugTest < Minitest::Test
def test_update_attribute_callbacks_broken
post = Post.create!(new_slug: "test-slug")
assert_equal post.slug, "test-slug"
post.update_attribute(:new_slug, "new-slug")
post.reload
assert_equal "new-slug", post.slug
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment