You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ruby on Rails视图中渲染嵌套JSON对象内的内容

解决方案

1. 视图嵌套属性获取方法

你当前的写法错误原因是:Ruby的Hash对象不支持将点号语法直接作为键名查找嵌套属性,你写的@post["heroimage.url"]是把heroimage.url整个当作顶层键查找,自然找不到对应值。
正确写法如下:

  • 基础写法(确定接口一定返回heroimage字段时使用):
    <p><%= @post["heroimage"]["url"] %></p>
    
  • 安全写法(避免heroimage为空时抛出异常,更推荐):
    可以用Hash自带的dig方法,多层嵌套也能自动处理中间层为空的情况,不会报错:
    <p><%= @post.dig("heroimage", "url") %></p>
    
    如果需要获取更深层级的属性,比如heroimage下large规格的图片地址,写法如下:
    <p><%= @post.dig("heroimage", "formats", "large", "url") %></p>
    

2. Controller代码优化

你当前的Controller代码存在两个问题,可能会导致异常:

  1. 同一路径重复发送两次HTTP请求,造成不必要的性能损耗
  2. 代码中引用的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 17:54:03