I'm really new to JSON so I apologise if this problem is trivial.
I am working on implementing an in-app notification feature for a ruby on rails project and successfully did so. However, my app has different models and I'm not sure how to customise the url in JSON. Right now, it only works for entry_path but I would like it to be able to get the URL for other objects. Also, I was wondering if it is possible to change the a to an for json.type depending on the context. 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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.