Rails 7.1.3.4中render json传map块与变量返回结果不同的原因
Rails渲染JSON时map直接传参异常的原因
问题场景
使用Rails 7.1.3.4和Ruby 3.3.4环境,控制器中编写如下代码:
render json: item.item_tags.map do |item_tag| { things_count: item_tag.tag.things.count, other_count: item_tag.tag.other_association.count, tag: { id: item_tag.tag.id, name: item_tag.tag.name, slug: item_tag.tag.slug, things: ThingSerializer.new.index(item_tag.tag.things), } } end
本应返回map处理后的自定义结构列表,但实际返回默认的item_tags列表:
[{ "id": 236, "status": "draft", "position": 0, "item_id": 234, "tag_id": 123, "inserted_at": "2024-03-19T10:23:56.000+03:00", "updated_at": "2024-03-19T10:23:56.000+03:00" }]
但将map结果先赋值给变量再传入render则正常:
actual_json = item.item_tags.map do |item_tag| { things_count: item_tag.tag.things.count, other_count: item_tag.tag.other_association.count, tag: { id: item_tag.tag.id, name: item_tag.tag.name, slug: item_tag.tag.slug, things: ThingSerializer.new.index(item_tag.tag.things), } } end render json: actual_json
原因分析
这是Ruby代码块绑定优先级差异导致的:
- 当直接使用
do...end代码块作为render json:的参数时,Ruby会把do...end绑定给render方法,而非map方法。此时map没有接收到预期的转换代码块,会直接返回原始的item_tagsActiveRecord集合;render接收到原始集合后,就会用默认规则序列化输出item_tags的数据库字段。 - 先将map结果赋值给变量时,
do...end会明确绑定给map方法,生成预期的自定义哈希数组,再传给render就能正确序列化。
替代解决方案
如果不想用变量中转,可以把do...end换成绑定优先级更高的{...}大括号写法,代码也能正常运行:
render json: item.item_tags.map { |item_tag| { things_count: item_tag.tag.things.count, other_count: item_tag.tag.other_association.count, tag: { id: item_tag.tag.id, name: item_tag.tag.name, slug: item_tag.tag.slug, things: ThingSerializer.new.index(item_tag.tag.things), } } }
内容的提问来源于stack exchange,提问作者Abdullah Esmail
相关产品推荐
相关产品推荐

