如何解决Blueprinter gem - 渲染 STI 集合
我正在尝试使用新的序列化替代方法:Blueprinter
如果每个模型都是某种类型的视图,您如何处理 STI 集合?
我想出了这样的东西(在 AMS github 问题上看到了类似的代码):
def serialize_cards(cards)
cards.group_by(&:type).map do |type,cards|
case type
when 'TypeOneCard' then Api::V1::CardBlueprint.render(cards,view: :one)
when 'TypeTwoCard' then Api::V1::CardBlueprint.render(cards,view: :two)
else raise ArgumentError,"Unhandled event type '#{type}'"
end
end
end
为什么输出为带反斜杠的字符串:
[
"[{\"id\":27566,\"attachment\":null,\"avatar\":null,\"card_comments_count\":0,\"card_likes_count\":0,\"card_publisher\":\"group\",\"created_at\":\"2020-11-18T10:24:42.195+01:00\",\"description\":\"Ted,how many times have I told you to put the lid back on the peanut butter jar?! It’s this inconsiderate,immature jackassery that makes me feel like I’m living in The Real World House! And not the early days when they all had jobs and social consciences,I’m talking about Hawaii,and after!\",\"ends_at\":\"2021-02-06T23:55:00.000+01:00\",\"event_attendees_count\":0,\"group_name\":\"Cheeseburger - Herbes de Provence\",\"origin\":\"http://localhost:3000/dorfplatz/3\",\"origin_name\":\"Dardagny - Athenaz (Avusy)\",\"picture\":null,\"starts_at\":\"2020-11-21T00:00:00.718+01:00\",\"title\":\"The Doors\",\"type\":\"EventCard\",\"updated_at\":\"2020-11-19T10:25:49.467+01:00\",\"user_full_name\":\"Carolann Ritchie\"},{\"id\":28163,\"created_at\":\"2020-11-14T23:22:42.059+01:00\",\"description\":\"That’s life,you kNow,we never end up where you thought you wanted to be.\",\"ends_at\":\"2020-12-05T23:55:00.000+01:00\",\"starts_at\":\"2020-11-14T00:00:00.942+01:00\",\"title\":\"Iron Maiden\",\"updated_at\":\"2020-11-19T10:25:59.622+01:00\",\"user_full_name\":\"Reuben Kertzmann\"},{\"id\":24658,\"created_at\":\"2020-11-14T14:40:45.442+01:00\",\"description\":\"You can’t just skip ahead to where you think your life should be.\",\"ends_at\":\"2021-02-04T23:55:00.000+01:00\",\"starts_at\":\"2020-11-19T00:00:00.811+01:00\",\"title\":\"Steely Dan\",\"updated_at\":\"2020-11-19T10:24:58.452+01:00\",\"user_full_name\":\"Reuben Kertzmann\"}]",
解决方法
使用 render_to_hash
而不是将每个序列化器输出为 JSON
def serialize_cards(cards)
cards.group_by(&:type).map do |type,cards|
case type
when 'TypeOneCard'
Api::V1::CardBlueprint.render_to_hash(cards,view: :one)
when 'TypeTwoCard'
Api::V1::CardBlueprint.render_to_hash(cards,view: :two)
else
raise ArgumentError,"Unhandled event type '#{type}'"
end
end
end
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。