2

I started to use the mongoid gem in my project, and I'm a little confused about how it store and get the information on the database. I have fields of specifics types in my models, but when I get it from the DB it returns a Hash. Here is my models:

service.rb

class Service
  include Mongoid::Document
  field :username, type: String
  field :strategy, type: Strategy
  field :design, type: Design

end

strategy.rb

class Strategy 
  include Mongoid::Document

  field :name, type: String
  field :description, type:  String
  field :resources, type:  Resources
  field :scalability, type:  Scalability  
  field :localization, type:  Localization
  field :contact, type:  Contact

end

If I initialize a new service @service, and do @service.class it returns Service, the right one, but if I try do @service.strategy.class, it returns Hash, and not Strategy, like I was expecting. I read on the mongoid manual there are the "Custom field serialization", what I think allows me to do what I want. But I was wondering if there are not any other way to do that easily, because I have lots of models to change.

lucianthomaz
  • 195
  • 3
  • 13
  • For custom field, you need to define how to serialize and deserialize them (3 methods needed). I don't see you defined them. – HungryCoder Nov 08 '12 at 17:48
  • It's the point HungryCoder, I just started with mongoid, and I was confused about that. It's the only way to achieve that? I have to define this 3 methods for how to serialize and deserialize in all the models I have defined custom fields? – lucianthomaz Nov 08 '12 at 18:01
  • 1
    @lucianthomaz Yes, that is what you have to do to store a type that Mongoid doesn't natively support. What might be a better technique is to store those objects as documents themselves, and use relationships (1-1, 1-n, etc) to connect them. That may (or may not) be a better solution than serializing your custom objects into fields. – Paul Hoffer Nov 09 '12 at 00:29
  • Thanks @phoffer, I'll start to change all my models to include these methods of serializing so. – lucianthomaz Nov 09 '12 at 11:21

0 Answers0