简体   繁体   English

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

[英]Customising JSON response in ruby on rails

I'm really new to JSON so I apologise if this problem is trivial.我对 JSON 真的很陌生,所以如果这个问题是微不足道的,我深表歉意。

I am working on implementing an in-app notification feature for a ruby on rails project and successfully did so.我正在为 Rails 项目上的 ruby 实施应用内通知功能,并成功地做到了。 However, my app has different models and I'm not sure how to customise the url in JSON.但是,我的应用程序有不同的型号,我不确定如何在 JSON 中自定义 url。 Right now, it only works for entry_path but I would like it to be able to get the URL for other objects.现在,它仅适用于 entry_path,但我希望它能够为其他对象获取 URL。 Also, I was wondering if it is possible to change the a to an for json.type depending on the context.另外,我想知道是否可以根据上下文将 json.type 的 a 更改为 an。 Thank you and any help is greatly appreciated!谢谢您,非常感谢您的帮助!

 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

I think a more scalable solution would be to override the notification class as_json method.我认为一个更具可扩展性的解决方案是覆盖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

and then you can call notification.to_json in your loop然后你可以在你的循环中调用notification.to_json

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

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