繁体   English   中英

在轨道上的 ruby 中自定义 JSON 响应

[英]Customising JSON response in ruby on rails

我对 JSON 真的很陌生,所以如果这个问题是微不足道的,我深表歉意。

我正在为 Rails 项目上的 ruby 实施应用内通知功能,并成功地做到了。 但是,我的应用程序有不同的型号,我不确定如何在 JSON 中自定义 url。 现在,它仅适用于 entry_path,但我希望它能够为其他对象获取 URL。 另外,我想知道是否可以根据上下文将 json.type 的 a 更改为 an。 谢谢您,非常感谢您的帮助!

 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 class 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM