Skip to content

acts_as_api and Mongoid

fabrik42 edited this page May 14, 2011 · 4 revisions

acts_as_api and Mongoid

Even though most examples in this wiki are based on ActiveRecord, acts_as_api comes also with support for the fantastic Mongoid gem.

Good thing: You don't need to configure anything special, it should just work out of the box.

Also, acts_as_api provides exactly the same interface for ActiveRecord as well as for Mongoid.

This means you can reuse all examples on this wiki for MongoDB. :)

Not working out of the box?

It should work out of the box, but sometimes there can be problems with the order of inclusion of the mongoid gem (must be loaded first) and the acts_as_api gem. #

In this case just add the following snippet, e.g. in a file in your /config/initializers folder of your Rails project:

# Attach ourselves to Mongoid
if defined?(Mongoid::Document)
  Mongoid::Document.send :include, ActsAsApi::Adapters::Mongoid
end

Example with Mongoid

class User
  include Mongoid::Document
  
  field :first_name, :type => String
  field :last_name, :type => String
  field :age, :type => Integer
  field :active, :type => Boolean

  acts_as_api

  api_accessible :name_only do |template|
    template.add :first_name
    template.add :last_name
  end

end