File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -60,6 +60,10 @@ def belongs_to?
6060 false
6161 end
6262
63+ def readonly?
64+ @options [ :readonly ]
65+ end
66+
6367 class ToOne < Relationship
6468 attr_reader :foreign_key_on
6569
Original file line number Diff line number Diff line change @@ -580,12 +580,12 @@ def cache_field(field)
580580
581581 # Override in your resource to filter the updatable keys
582582 def updatable_fields ( _context = nil )
583- _updatable_relationships | _attributes . keys - [ :id ]
583+ _updatable_relationships | _updatable_attributes - [ :id ]
584584 end
585585
586586 # Override in your resource to filter the creatable keys
587587 def creatable_fields ( _context = nil )
588- _updatable_relationships | _attributes . keys
588+ _updatable_relationships | _updatable_attributes
589589 end
590590
591591 # Override in your resource to filter the sortable keys
@@ -891,8 +891,12 @@ def _attribute_options(attr)
891891 default_attribute_options . merge ( @_attributes [ attr ] )
892892 end
893893
894+ def _updatable_attributes
895+ _attributes . map { |key , options | key unless options [ :readonly ] } . compact
896+ end
897+
894898 def _updatable_relationships
895- @_relationships . map { |key , _relationship | key }
899+ @_relationships . map { |key , relationship | key unless relationship . readonly? } . compact
896900 end
897901
898902 def _relationship ( type )
Original file line number Diff line number Diff line change @@ -98,6 +98,11 @@ class RelatedResource < MyModule::RelatedResource
9898 end
9999end
100100
101+ class PostWithReadonlyAttributesResource < JSONAPI ::Resource
102+ attribute :title , readonly : true
103+ has_one :author , readonly : true
104+ end
105+
101106class ResourceTest < ActiveSupport ::TestCase
102107 def setup
103108 @post = Post . first
@@ -629,4 +634,12 @@ def test_resources_for_transforms_records_into_resources
629634 resources = PostResource . resources_for ( [ Post . first ] , { } )
630635 assert_equal ( PostResource , resources . first . class )
631636 end
637+
638+ def test_readonly_attribute
639+ refute_includes ( PostWithReadonlyAttributesResource . creatable_fields , :title )
640+ refute_includes ( PostWithReadonlyAttributesResource . updatable_fields , :title )
641+
642+ refute_includes ( PostWithReadonlyAttributesResource . creatable_fields , :author )
643+ refute_includes ( PostWithReadonlyAttributesResource . updatable_fields , :author )
644+ end
632645end
You can’t perform that action at this time.
0 commit comments