From fe29d6511f39c52b8d2ff7c4f9955d1a9dfef088 Mon Sep 17 00:00:00 2001 From: moznion Date: Thu, 7 Aug 2025 11:14:20 +0900 Subject: [PATCH 1/2] Fix model_name availability when using ActiveModel::Serialization In v4.0.0, switching from `extend ActiveModel::Naming` to only `extend ActiveModel::Translation` can cause "undefined method 'model_name'" errors when ActiveHash models include ActiveModel::Serialization, particularly with Rails 8.0+. While ActiveModel::Translation includes ActiveModel::Naming internally, the inclusion doesn't always properly expose the model_name class method when extended. This breaks compatibility for models that depend on model_name being available at the class level. This commit explicitly extends both ActiveModel::Naming and ActiveModel::Translation to ensure model_name is always available while maintaining i18n support. This approach ensures compatibility across all Rails versions. Signed-off-by: moznion --- lib/active_hash/base.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/active_hash/base.rb b/lib/active_hash/base.rb index ab43762..4bffad2 100644 --- a/lib/active_hash/base.rb +++ b/lib/active_hash/base.rb @@ -24,6 +24,7 @@ class Base class_attribute :_data, :dirty, :default_attributes, :scopes if Object.const_defined?(:ActiveModel) + extend ActiveModel::Naming extend ActiveModel::Translation include ActiveModel::Conversion else From 9c4af3964012c51f8dae936542c3b184ed91deea Mon Sep 17 00:00:00 2001 From: moznion Date: Tue, 12 Aug 2025 22:31:22 +0900 Subject: [PATCH 2/2] Add a test case to ensure that calling `#model_name` on ActiveHash::Base does not raise a NoMethodError Signed-off-by: moznion --- spec/active_hash/base_spec.rb | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/spec/active_hash/base_spec.rb b/spec/active_hash/base_spec.rb index 4ff3099..c268815 100644 --- a/spec/active_hash/base_spec.rb +++ b/spec/active_hash/base_spec.rb @@ -1732,6 +1732,17 @@ class Book < ActiveRecord::Base end + describe "#model_name" do + # This test reproduces the issue reported in https://github.com/active-hash/active_hash/pull/335, + # regarding whether ActiveHash (and its derived models) expose `#model_name`. + # Some serializers (e.g., okuramasafumi/alba) use the `#model_name` method internally, + # so this test ensures that a NoMethodError is not raised. + it "exposes model_name correctly" do + instance = Country.new(:id => 1) + expect { instance.model_name }.not_to raise_error + end + end + describe ".transaction" do it "execute the block given to it" do