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.2k stars 179 forks source link

Can a class that inherits from ActiveHash::Base be associated with another class that inherits from ActiveHash::Base? #238

Closed mattandayo closed 9 months ago

mattandayo commented 2 years ago

Hi ✋ Thank you for developing a great gem!!

I expect the following behavior.

class Category < ActiveHash::Base
  include ActiveHash::Associations

  has_many :children, foreign_key: :parent_id, class_name: ChildCategory.to_s

  fields :name
  add id: 1, name: 'name'
  add id: 2, name: 'name'
end

class ChildCategory < ActiveHash::Base
  extend ActiveHash::Associations::ActiveRecordExtensions

  belongs_to_active_hash :parent, foreign_key: :parent_id, class_name: Category.to_s

  fields :parent_id, :name
  add id: 1, parent_id: 1, name: 'name'
  add id: 2, parent_id: 2, name: 'name'
end

$ Category.last.children
=> #<ActiveHash::Relation ...

$ ChildCategory.last.parent
=> #<Category ...

However, I get errors

$ Category.last.children
=> /usr/local/bundle/gems/active_hash-3.1.0/lib/active_hash/base.rb:247:in `method_missing': undefined method `clear_reflections_cache' for ChildCategory:Class (NoMethodError)

$ ChildCategory.last.parent
=> /usr/local/bundle/gems/active_hash-3.1.0/lib/active_hash/base.rb:247:in `method_missing': undefined method `clear_reflections_cache' for ChildCategory:Class (NoMethodError)

Please tell me what the problem is.

Environment

kbrock commented 9 months ago
require "active_hash"

class Category < ActiveHash::Base
  include ActiveHash::Associations

  has_many :children, foreign_key: :parent_id, class_name: "ChildCategory"

  fields :name
  add id: 1, name: 'name'
  add id: 2, name: 'name'
end

class ChildCategory < ActiveHash::Base
  include ActiveHash::Associations

  belongs_to :parent, foreign_key: :parent_id, class_name: "Category"

  fields :parent_id, :name
  add id: 1, parent_id: 1, name: 'name'
  add id: 2, parent_id: 2, name: 'name'

end

puts Category.last.children
puts ChildCategory.last.parent

let me know if that gives you issues