active-hash / active_hash

A readonly ActiveRecord-esque base class that lets you use a hash, a Yaml file or a custom file as the datasource
MIT License
1.19k stars 178 forks source link

No Method Error for find_by and find #283

Closed thoughtbot-boost-support closed 1 year ago

thoughtbot-boost-support commented 1 year ago

I have recently updated my app to rails 7.0.5 and Ruby 3.2.2. It looks like the files that were inheriting from ActiveHash::Base now no longer have access to Active Record methods. They are treated as an array of hashes. I have not changed the code for them, I only updated the gems.

The repo is private so I'm not sure what I can share. The rest of the team is off work already so I will have to wait until tomorrow to find out what I can share.

example of code

# app/models/doodle/base.rb
require "active_hash"

class Doodle::Base < ActiveRecord::Base
  self.abstract_class = true
  extend ActiveHash::Associations::ActiveRecordExtensions
end
# app/models/doodle/display_mode.rb
class Doodle::DisplayMode < ActiveHash::Base
  self.data = [
    {position: 1, id: 1, name: "SomeName", long_name: "LongName"},
    {position: 2, id: 2, name: "OtherName", long_name: "OtherLongName", doodle_name: "OtherName (OtherName-Yellow)"},
    {position: 3, id: 6, name: OtherName-Blue"},
    {position: 4, id: 7, name: "OtherName-Gray"},
  ]

  def self.all
    super.sort_by(&:position)
  end

  def doodle_name
    attributes[:doodle_name] || name
  end
end

Doodle::DisplayMode.find(1).name

Error

undefined method `name' for #<Enumerator: [#<Doodle::DisplayMode:0x00000001065492f8 @attributes={:position=>1, :id=>1, :name=>"SomeName", :long_name=>"LongName"}>, #<Doodle::DisplayMode:0x0000000106548178 @attributes={:position=>2, :id=>2, :name=>"OtherName", :long_name=>"OtherLongName", :doogle_name=>"OtherName (OtherName-Yellow)"}>, #<Doodle::DisplayMode:0x0000000106545338 @attributes={:position=>3, :id=>6, :name=>"OtherName-Blue"}>, #<Doodle::DisplayMode:0x00000001065445c8 @attributes={:position=>4, :id=>7, :name=>"OtherName-Gray"}>>]:find(1)>
thoughtbot-boost-support commented 1 year ago

We found there there was a method overwriting the all method from ActiveHash::Base that was causing the issue. The method was removed and we were able to upgrade the active_hash gem without breaking the code.