Skip to content

Commit

Permalink
Merge branch '8.1-stable' into 5822-embedded-association-validations-…
Browse files Browse the repository at this point in the history
…break-backport-8.1
  • Loading branch information
DarshanaVenkatesh authored Dec 18, 2024
2 parents 9c7d0c1 + c3054b3 commit 0390ba2
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
11 changes: 8 additions & 3 deletions lib/mongoid/attributes/readonly.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ module Readonly
# @return [ true | false ] If the document is new, or if the field is not
# readonly.
def attribute_writable?(name)
new_record? || (!readonly_attributes.include?(name) && _loaded?(name))
new_record? || (!self.class.readonly_attributes.include?(name) && _loaded?(name))
end

private
Expand Down Expand Up @@ -62,12 +62,17 @@ module ClassMethods
# end
#
# @param [ Symbol... ] *names The names of the fields.
# @note When a parent class contains readonly attributes and is then
# inherited by a child class, the child class will inherit the
# parent's readonly attributes at the time of its creation.
# Updating the parent does not propagate down to child classes after wards.
def attr_readonly(*names)
self.readonly_attributes = self.readonly_attributes.dup
names.each do |name|
readonly_attributes << database_field_name(name)
self.readonly_attributes << database_field_name(name)
end
end
end
end
end
end
end
19 changes: 19 additions & 0 deletions spec/mongoid/attributes/readonly_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,26 @@
expect(child.mother).to be_nil
end
end
end

context "when a subclass inherits readonly fields" do
let(:attributes) do
[:title, :terms]
end

before do
class OldPerson < Person
attr_readonly :age
end
end

it "ensures subclass inherits the readonly attributes from parent" do
expect(OldPerson.readonly_attributes.to_a).to include("title","terms")
end

it "ensures subclass does not modify parent's readonly attributes" do
expect(Person.readonly_attributes.to_a).not_to include("age")
end
end
end
end

0 comments on commit 0390ba2

Please sign in to comment.