假设我们有类似的东西:
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,包括链接和其他额外的序列化数据.
解决方法
事实证明,使用
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)