ruby-on-rails - 在 ruby on rails 中自定义 JSON 响应
问题描述
我对 JSON 很陌生,所以如果这个问题是微不足道的,我深表歉意。
我正在为 ruby on rails 项目实施应用内通知功能,并成功地做到了。但是,我的应用程序有不同的模型,我不确定如何自定义 JSON 中的 url。现在,它只适用于 entry_path 但我希望它能够获取其他对象的 URL。另外,我想知道是否可以根据上下文将 a 更改为 json.type 。谢谢您,非常感谢您的帮助!
json.array! @notifications do |notification|
#json.recipient notification.recipient
json.id notification.id
json.actor notification.actor.firstname
json.action notification.action
json.title notification.title
json.notifiable do
json.type "a #{notification.notifiable.class.to_s.underscore.humanize.downcase}"
end
json.url entry_path(notification.notifiable.entry, anchor: dom_id(notification.notifiable))
end
解决方案
我认为一个更具可扩展性的解决方案是覆盖notification
类as_json
方法。
class Notification
def as_json
{
id: id
actor: actor.firstname
action: action
title: title
notifiable: {type: get_type}
url: get_url
}
end
def get_type
# Type logic
end
def get_url
# url logic
end
end
然后你可以notification.to_json
在你的循环中调用
推荐阅读
- java - 如何从绝对路径获取包名?
- java - 嵌套级别的 Java 8 流优化
- python - 比较 Python 中的特殊字符
- ios - Can't push view controller in AppDelegate with TabBarController
- javascript - [Vue 警告]:渲染错误:“TypeError:无法获取未定义或空引用的属性‘Id’
- web-services - 使用 Jetty 配置的 Restlet
- c - 清除c中的数组数据
- php - Wamp 服务器中的错误显示错误:路径中的 C:/wamp 或 PHP
- java - 从unix机器识别windows selenium节点中下载的文件
- xamarin - 取消勾选“使用共享运行时”会产生性能问题