ruby – 与Roar的关联和收藏
发布时间:2020-12-16 23:31:17 所属栏目:百科 来源:网络整理
导读:假设我们有类似的东西: class Company include Mongoid::Document has_many :users field :name,type: Stringendclass User include Mongoid::Document belongs_to :company field :name,type: Stringendmodule CompanyRepresenter include Roar::Represent
假设我们有类似的东西:
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) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- c# – 如何在不参考System.Web的情况下检查Web.Config中的身
- actionscript-3 – 字符串的长度(以像素为单位)
- 零React基础入门Amaze UI Touch!
- solr4.7.1 schema.xml
- cocos2dx 3.3 quick lua 实现返回键退出程序
- cocos2d-x学习笔记(8)ScaleTo和ScaleBy 以及 Blink
- ruby – 在CSV文件中跳过标题前的行
- ruby-on-rails – “更新”的“Rails方式”是否存在根本缺陷
- 连接到PostgreSQL服务器:致命:主机没有pg_hba.conf条目
- objective-c – CBPeripheral name有时为空