@@ -84,6 +84,10 @@ class NonRaisingPost < Post
84
84
85
85
ActiveRecord . raise_on_assign_to_attr_readonly = previous_value
86
86
87
+ class ReadonlyAuthorPost < Post
88
+ attr_readonly :author_id
89
+ end
90
+
87
91
class Weird < ActiveRecord ::Base ; end
88
92
89
93
class LintTest < ActiveRecord ::TestCase
@@ -844,6 +848,33 @@ def test_readonly_attributes_when_configured_to_not_raise
844
848
assert_equal "changed via []=" , post . body
845
849
end
846
850
851
+ def test_readonly_attributes_on_belongs_to_association
852
+ assert_equal [ "author_id" ] , ReadonlyAuthorPost . readonly_attributes
853
+
854
+ author1 = Author . create! ( name : "Alex" )
855
+ author2 = Author . create! ( name : "Not Alex" )
856
+
857
+ post_with_reload = ReadonlyAuthorPost . create! ( author : author1 , title : "Hi" , body : "there" )
858
+ post_with_reload . reload
859
+ post_with_reload . update ( title : "Hello" , body : "world" )
860
+ assert_equal author1 , post_with_reload . author
861
+
862
+ post_with_reload2 = ReadonlyAuthorPost . create! ( author : author1 , title : "Hi" , body : "there" )
863
+ post_with_reload2 . reload
864
+ assert_raises ( ActiveRecord ::ReadonlyAttributeError ) do
865
+ post_with_reload2 . update ( author : author2 )
866
+ end
867
+
868
+ post_without_reload = ReadonlyAuthorPost . create! ( author : author1 , title : "Hi" , body : "there" )
869
+ post_without_reload . update ( title : "Hello" , body : "world" )
870
+ assert_equal author1 , post_without_reload . author
871
+
872
+ post_without_reload2 = ReadonlyAuthorPost . create! ( author : author1 , title : "Hi" , body : "there" )
873
+ assert_raises ( ActiveRecord ::ReadonlyAttributeError ) do
874
+ post_without_reload2 . update ( author : author2 )
875
+ end
876
+ end
877
+
847
878
def test_unicode_column_name
848
879
Weird . reset_column_information
849
880
weird = Weird . create ( なまえ : "たこ焼き仮面" )
0 commit comments