如何使用Rails Jbuilder提取所有属性?

在jbuilder.json模板中一直编写这样的代码是一件痛苦的事:

json.extract! notification, :id, :user_id, :notice_type, :message, :resource_type, :resource_id, :unread, :created_at, :updated_at 

所以我想这样编码;

 json.extract_all! notification 

我发现我可以像下面的代码那样做,但它们对我来说仍然有点冗长。

 notification.attributes.each do |key, value| json.set!(key, value) end 

有没有更好的方法?

也许你可以使用json.merge!

 json.merge! notification.attributes 

https://github.com/rails/jbuilder/blob/master/lib/jbuilder.rb#L277

我正在使用jbuilder 1.5.0并合并! 没用,但我找到了另一种语法:

 json.(notification, *notification.attributes.keys) 

添加更多@uiureo的答案

假设您的通知具有某种类型的图像上传器(例如载波,回形针)

那么下面的版本将不会返回你的上传者对象,那你如何获得图片url?

 json.merge! notification.attributes 

notification.attributes是对象的哈希转换,它将返回挂载的上传列值而不是url。

样品回复

 notification: Object { title: "hellow world" img: "sample.png" } 

而是试试这个

 json.merge! notification.as_json 

这将把已安装的列作为另一个对象返回,您可以在其中查询url。

样品回复

 notification: Object { title: "hellow world" img: Object { url: "https://www.example.com/sample.png" } } 

你可以看看json.except!

json.except! @resource, :id, :updated_at

json.except! @resource

https://github.com/chenqingspring/jbuilder-except