Skip to content

Commit

Permalink
update attribute_builder for rails change
Browse files Browse the repository at this point in the history
rails 5.0.7 changed the way attribute_builder works
This updates attribute_builder to work accordingly

Also, 5.0.0 changed the way dirty worked.
Think the change to forgetting_assignment introduced this problem for
all rails versions, but it is subtle and would only be noticed by
people who use lots of non-database attributes (e.g.: us)
It remains in 5.1.0 but the code changes significantly in 5.2
  • Loading branch information
kbrock committed Sep 25, 2018
1 parent 9f3c401 commit a687c22
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
25 changes: 20 additions & 5 deletions lib/extensions/ar_virtual.rb
Original file line number Diff line number Diff line change
Expand Up @@ -400,12 +400,15 @@ def virtual_attribute_names
end
end

def attributes_builder
@attributes_builder ||= ::ActiveRecord::AttributeSet::Builder.new(attribute_types, primary_key) do |name|
unless columns_hash.key?(name) || virtual_attribute?(name)
_default_attributes[name].dup
end
def attributes_builder # :nodoc:
unless defined?(@attributes_builder) && @attributes_builder
defaults = _default_attributes.except(*(column_names - [primary_key]))
# change necessary for rails 5.0 and 5.1 - (changed/introduced in https://github.com/rails/rails/pull/31894)
defaults = defaults.except(*virtual_attribute_names)
# end change
@attributes_builder = ActiveRecord::AttributeSet::Builder.new(attribute_types, defaults)
end
@attributes_builder
end

private
Expand Down Expand Up @@ -597,6 +600,18 @@ def remove_virtual_fields(associations)
# Class extensions
#

# this patch is no longer necessary for 5.2
require "active_record/attribute"
module ActiveRecord
# This is a bug in rails 5.0 and 5.1, but it is made much worse by virtual attributes
class Attribute
def with_value_from_database(value)
# self.class.from_database(name, value, type)
initialized? ? self.class.from_database(name, value, type) : self
end
end
end

module ActiveRecord
class Base
include VirtualFields
Expand Down
9 changes: 9 additions & 0 deletions spec/lib/extensions/ar_virtual_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -981,6 +981,15 @@ def col2
end
end

describe "ActiveRecord attributes" do
it "doesn't botch up the attributes" do
hardware = Hardware.select(:id, :model).find(FactoryGirl.create(:hardware).id)
expect(hardware.attributes.size).to eq(2)
hardware.save
expect(hardware.attributes.size).to eq(2)
end
end

describe "ApplicationRecord class" do
describe ".virtual_attribute_names" do
it "class immediately under ApplicationRecord" do
Expand Down

0 comments on commit a687c22

Please sign in to comment.