Skip to content

Commit 6d3aedb

Browse files
authored
Merge pull request rails#43263 from bnjamin/filter-virtual-columns
Filter virtual columns from the attribute names
2 parents 50d60e4 + a3a797e commit 6d3aedb

File tree

3 files changed

+20
-4
lines changed

3 files changed

+20
-4
lines changed

activerecord/lib/active_record/attribute_methods.rb

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -387,20 +387,22 @@ def attributes_with_values(attribute_names)
387387
attribute_names.index_with { |name| @attributes[name] }
388388
end
389389

390-
# Filters the primary keys and readonly attributes from the attribute names.
390+
# Filters the primary keys, readonly attributes and virtual columns from the attribute names.
391391
def attributes_for_update(attribute_names)
392392
attribute_names &= self.class.column_names
393393
attribute_names.delete_if do |name|
394-
self.class.readonly_attribute?(name)
394+
self.class.readonly_attribute?(name) ||
395+
column_for_attribute(name).virtual?
395396
end
396397
end
397398

398-
# Filters out the primary keys, from the attribute names, when the primary
399+
# Filters out the virtual columns and also primary keys, from the attribute names, when the primary
399400
# key is to be generated (e.g. the id attribute has no value).
400401
def attributes_for_create(attribute_names)
401402
attribute_names &= self.class.column_names
402403
attribute_names.delete_if do |name|
403-
pk_attribute?(name) && id.nil?
404+
(pk_attribute?(name) && id.nil?) ||
405+
column_for_attribute(name).virtual?
404406
end
405407
end
406408

activerecord/lib/active_record/connection_adapters/column.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,10 @@ def hash
8787
comment.hash
8888
end
8989

90+
def virtual?
91+
false
92+
end
93+
9094
private
9195
def deduplicated
9296
@name = -name

activerecord/test/cases/adapters/postgresql/virtual_column_test.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,16 @@ def setup
2323
VirtualColumn.create(name: "Rails")
2424
end
2525

26+
def test_virtual_column_with_full_inserts
27+
partial_inserts_was = VirtualColumn.partial_inserts
28+
VirtualColumn.partial_inserts = false
29+
assert_nothing_raised do
30+
VirtualColumn.create!(name: "Rails")
31+
end
32+
ensure
33+
VirtualColumn.partial_inserts = partial_inserts_was
34+
end
35+
2636
def teardown
2737
@connection.drop_table :virtual_columns, if_exists: true
2838
VirtualColumn.reset_column_information

0 commit comments

Comments
 (0)