Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associations and collections with Roar

Tags:

rest

ruby

mongoid

Assume we have something like:

class Company
  include Mongoid::Document
  has_many :users
  field :name, type: String
end

class User
  include Mongoid::Document
  belongs_to :company
  field :name, type: String
end

module CompanyRepresenter
  include Roar::Representer::JSON 
  property :name
end

module UserRepresenter
  include Roar::Representer::JSON 
  property :name
  link :self do
    user_url
  end
end

Then we go on to do something like this:

user.extend(UserRepresenter).to_json

And everything is just great. But how about:

User.all.to_json

or:

company.extend(CompanyRepresenter).users.to_json?

or even:

company.users.collect{|u| u.extend(UserRepresenter)}.extend(Representable::JSON::Collection).to_json

The result is always an array of Mongoid's normal to_json entries.

The question is how do I get something like Company.all.to_json to have Roared JSONs including the links and other extra serialization data.

like image 796
Kimmo Lehto Avatar asked Mar 02 '12 13:03

Kimmo Lehto


1 Answers

It turns out this is simple to achieve using Representable (which is used by Roar):

require 'roar/representer/json'

module PostRepresenter
  include Roar::Representer::JSON

  property :id
  property :title
end

require 'representable/json/collection'

module PostsRepresenter
  include Representable::JSON::Collection

  items extend: PostRepresenter
end

Post.limit(10).extend(PostsRepresenter)
like image 149
benpickles Avatar answered Sep 20 '22 04:09

benpickles