user1311034
user1311034

Reputation: 261

Mongoid and collections

I am trying to configure and use mongoid for the first time. I have set the mongoid.yml config file simply as:

host: localhost

database: table

and my code:

  Mongoid.load!("/mongoid.yml") 
  class Data        
    include Mongoid::Document
    field :study, type: String
    field :nbc_id, type: String
    field :short_title, type: String
    field :source, type: String
    field :start_date, type: Date
  end

  puts Data.study

I keep getting an error:

NoMethodError at / undefined method `study' for Data:Class

I think it is because I have not specified the collection name which is 'test'. However I can find no examples on how to do this. Do I specify it in the .yml file or in the code. What is the correct syntax. Can anyone point me in the right direction?

Tx.

Upvotes: 1

Views: 1710

Answers (1)

Marc
Marc

Reputation: 5548

According to the Mongoid documentation, "Mongoid by default stores documents in a collection that is the pluralized form of the class name. For the following Person class, the collection the document would get stored in would be named people." http://mongoid.org/docs/documents.html

The documentation goes on to state that Mongoid uses a method called ActiveSupport::Inflector#classify to determine collection names, and provides instructions on how to specify the plural yourself.

Alternatively, you can specify the collection name in your class by including "store_in" in your class definition.

class Data        
    include Mongoid::Document
    store_in :test

Hope this helps!

Upvotes: 2

Related Questions