I have an API, built on Rails 4.2.6, and using active-model-serializers 0.10.0. While ams is great, I want to return a key and value that don't represent columns on the table. The API is used to create a letter, and I need to return the url that the user can find that letter at. Something along the lines of:
https://{DOMAIN}.com/letters/{LETTER.ID}
Do I modify the serializer somehow to do this, or do I render some custom JSON that includes the serializer information in it? I've checked a couple of other questions that have to do with custom JSON output, but they don't cover this question specifically.
EDIT
I tried your method below, @max, although I'm not sure it's quite what you meant. Here is what I added to my serializer:
attributes :id, :url, :date_created, etc...
def url
"https://{www.example.com/previewpdf/mailings/#{id}"
end
I tried both this, and using self.id, but both return an "undefined method 'id'" error, so I'll keep plugging away.
EDIT #2 I switched to using :id instead of id, and that made the undefined method error disappear, but the url is showing up in the JSON as
https://www.example.com/pdfpreview?SubOrderId=id
When I need that last part to read SubOrderId=28291, or whatever the id is of the mailing being created.
EDIT
This is still perplexing me, does anyone know how to include the actual value of the id key in a custom string response?
If a method with the same name as an attribute exists the serializer will call the method instead of getting the attribute directly from the object being serialized.
Note that the object being serialized does not need to have a
url
attribute.Another way to do this is by using
attribute
with a block: