Skip to content

Commit 0390ba2

Browse files
Merge branch '8.1-stable' into 5822-embedded-association-validations-break-backport-8.1
2 parents 9c7d0c1 + c3054b3 commit 0390ba2

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

Diff for: lib/mongoid/attributes/readonly.rb

+8-3
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ module Readonly
2222
# @return [ true | false ] If the document is new, or if the field is not
2323
# readonly.
2424
def attribute_writable?(name)
25-
new_record? || (!readonly_attributes.include?(name) && _loaded?(name))
25+
new_record? || (!self.class.readonly_attributes.include?(name) && _loaded?(name))
2626
end
2727

2828
private
@@ -62,12 +62,17 @@ module ClassMethods
6262
# end
6363
#
6464
# @param [ Symbol... ] *names The names of the fields.
65+
# @note When a parent class contains readonly attributes and is then
66+
# inherited by a child class, the child class will inherit the
67+
# parent's readonly attributes at the time of its creation.
68+
# Updating the parent does not propagate down to child classes after wards.
6569
def attr_readonly(*names)
70+
self.readonly_attributes = self.readonly_attributes.dup
6671
names.each do |name|
67-
readonly_attributes << database_field_name(name)
72+
self.readonly_attributes << database_field_name(name)
6873
end
6974
end
7075
end
7176
end
7277
end
73-
end
78+
end

Diff for: spec/mongoid/attributes/readonly_spec.rb

+19
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,26 @@
265265
expect(child.mother).to be_nil
266266
end
267267
end
268+
end
269+
270+
context "when a subclass inherits readonly fields" do
271+
let(:attributes) do
272+
[:title, :terms]
273+
end
274+
275+
before do
276+
class OldPerson < Person
277+
attr_readonly :age
278+
end
279+
end
268280

281+
it "ensures subclass inherits the readonly attributes from parent" do
282+
expect(OldPerson.readonly_attributes.to_a).to include("title","terms")
283+
end
284+
285+
it "ensures subclass does not modify parent's readonly attributes" do
286+
expect(Person.readonly_attributes.to_a).not_to include("age")
287+
end
269288
end
270289
end
271290
end

0 commit comments

Comments
 (0)