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

Rails中link_to路由问题:Active Storage图片跳转show页报错

解决Active Storage图片跳转News show页面的路由错误问题

错误原因很明确:你在_blob.html.erb里使用的@new变量没有被赋值,是nil,所以news_path(@new)无法生成有效的路由(缺少:id参数)。

要从关联的Blob找到对应的News记录,需要利用Active Storage和Action Text的关联关系:

  • Blob通过attachments关联到ActionText::Attachment
  • ActionText::Attachment的record属性就是对应的News实例

修改_blob.html.erb里的link_to代码,替换掉@new:

<figure class="attachment attachment--<%= blob.representable? ? "preview" : "file" %> attachment--<%= blob.filename.extension %>">
  <% if blob.representable? %>
    <%= link_to image_tag(blob.representation(resize_to_limit: local_assigns[:in_gallery] ? [800, 600] : [1024, 768])), news_path(blob.attachments.first&.record) if blob.attachments.first&.record.present? %>
  <% end %>

  <figcaption class="attachment__caption">
    <% if caption = blob.try(:caption) %>
      <%= caption %>
    <% else %>
      <span class="attachment__name"><%= blob.filename %></span>
      <span class="attachment__size"><%= number_to_human_size blob.byte_size %></span>
    <% end %>
  </figcaption>
</figure>

关键说明:

  • 使用blob.attachments.first&.record安全获取对应的News记录,&.是Ruby的安全导航操作符,避免当Blob没有关联Attachment时出现报错
  • 添加if blob.attachments.first&.record.present?判断,确保只有在找到有效News记录时才渲染链接,避免生成无效的路由

内容的提问来源于stack exchange,提问作者Vladimir Lozitskiy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 23:47:23