active-hash/active_hash

Creation working only after calling `Model.all`

Opened this issue · 1 comments

I have a model called Hotel which is using active yaml.

class Hotel < ActiveYaml::Base
  set_root_path Rails.root.join('db', 'yaml_data')
  set_filename 'hotel'
end

After going to rails c if I do Hotel.create(name: "A hotel name") it's throwing

NoMethodError (undefined method `name=' for #<Hotel:0x00007f7ff0ce7b98 @attributes={:name=>"name"}>)  

Anyway if i do the same after running Hotel.all. It's just working fine:

vailability-validation ~/repos/booking-engine> rails c
Running via Spring preloader in process 6236
Loading development environment (Rails 6.0.3.2)

irb(main):001:0> Hotel.create(name: "name")
Traceback (most recent call last):
           1: from (irb):1
NoMethodError (undefined method `name=' for #<Hotel:0x00007f7ff17106d8 @attributes={:name=>"name"}>)

irb(main):002:0> Hotel.all
 => #<ActiveHash::Relation:0x00007f7ff71e6300 @klass=Hotel, @all_records=[#<Hotel:0x00007f7ff71ef900 @attributes={:id=>1, :....... @query_hash={}, @records_dirty=false>

irb(main):003:0> Hotel.create(name: "name")
=> #<Hotel:0x00007f7ff710bb88 @attributes={:name=>"name", :id=>5}>

I have just used Hotel model for simplicity, but this is happenning on all yaml models.

This is documented in the readme https://github.com/zilkey/active_hash#auto-defined-fields. The fields are autoloaded once you call Model.all. To make them available before that, use the fields class method.