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
相关产品推荐
相关产品推荐

