vanboom
vanboom

Reputation: 1332

Undefined Class/Module when Serializing

I am storing an array of typed objects in an ActiveRecord model like:

class Store::Bin < ActiveRecord::Base
  serialize :items, Array
end

class Store::Item
   include Virtus.model
   attribute :name, String
   ...
end

When I make a code change in development mode and refresh my browser, I get an undefined class/module Store::Item exception.

It seems like something is getting crossed up with the class loading. All files are in the app/models/store/... directory, properly named w/r to their camelcase name.

The same issue happens when using the rails console. reload! does not fix the issue in the console; instead I have to exit and restart the console.

Upvotes: 2

Views: 1779

Answers (2)

vanboom
vanboom

Reputation: 1332

Adding a type to the array seemed to solve the problem.... but caused an issue with the associated FactoryGirl factory.

class Store::Bin < ActiveRecord::Base
  serialize :items, Array[Store::Item]
end

UPDATE: the real issue was that when a code change is made to store/bin.rb, that class gets auto-loaded, but the auto loader had no idea that Store::Item was a dependency.

THE REAL FIX: Declare the required dependency using require_dependency

require_dependency "store/item"
class Store::Bin < ActiveRecord::Base
  serialize :items, Array
end

Upvotes: 2

gkats
gkats

Reputation: 1332

You should avoid the :: operator when defining classes because of Rails autoload problems. Instead, try

module Store
  class Item
     # ...
  end
end

When you're not sure what's going on you can use Module.nesting to figure out how Rails interprets the hierarchy.

Upvotes: 0

Related Questions