首页 > 解决方案 > 在 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

标签: ruby-on-railsjsonruby

解决方案


我认为一个更具可扩展性的解决方案是覆盖notificationas_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在你的循环中调用


推荐阅读