如何在Ruby on Rails视图中渲染嵌套JSON对象内的内容
解决方案
1. 视图嵌套属性获取方法
你当前的写法错误原因是:Ruby的Hash对象不支持将点号语法直接作为键名查找嵌套属性,你写的@post["heroimage.url"]是把heroimage.url整个当作顶层键查找,自然找不到对应值。
正确写法如下:
- 基础写法(确定接口一定返回heroimage字段时使用):
<p><%= @post["heroimage"]["url"] %></p> - 安全写法(避免heroimage为空时抛出异常,更推荐):
可以用Hash自带的dig方法,多层嵌套也能自动处理中间层为空的情况,不会报错:
如果需要获取更深层级的属性,比如heroimage下large规格的图片地址,写法如下:<p><%= @post.dig("heroimage", "url") %></p><p><%= @post.dig("heroimage", "formats", "large", "url") %></p>
2. Controller代码优化
你当前的Controller代码存在两个问题,可能会导致异常:
- 同一路径重复发送两次HTTP请求,造成不必要的性能损耗
- 代码中引用的
response变量未定义,运行时会直接抛出异常
优化后的get私有方法参考:
private def get(path) @host = 'api.example.com' # 仅发送一次请求存储响应结果 api_response = HTTParty.get("https://#{@host}/#{path}") # 判断响应状态是否正常 return false unless api_response.success? # 按需赋值实例变量 @post = api_response @blog = api_response if path == 'posts' end
3. 扩展:直接渲染图片示例
如果需要直接在页面渲染heroimage图片,可以直接使用Rails内置的image_tag辅助方法:
<% hero_url = @post.dig("heroimage", "url") %> <% if hero_url.present? %> <%= image_tag hero_url, alt: @post.dig("heroimage", "alternativeText"), width: 750 %> <% end %>
内容的提问来源于stack exchange,提问作者Shoesack
相关产品推荐
相关产品推荐

