与咆哮的协会和收藏

时间:2012-03-02 13:11:32

标签: ruby rest mongoid

假设我们有类似的东西:

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

然后我们继续做这样的事情:

user.extend(UserRepresenter).to_json

一切都很棒。但是如何:

User.all.to_json

或:

company.extend(CompanyRepresenter).users.to_json?

甚至:

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

结果始终是Mongoid正常to_json条目的数组。

问题是如何让Company.all.to_json之类的东西拥有Roared JSON,包括链接和其他额外的序列化数据。

1 个答案:

答案 0 :(得分:8)

事实证明使用Representable(由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)