Rails博客Articles#show页面报错 侧边栏渲染最新文章调用each方法失败
错误原因与解决方案
你遇到的NoMethodError in Articles#show undefined method 'each' for nil:NilClass报错根因为:
渲染「latest articles」侧边栏局部视图时,用于循环遍历的文章列表实例变量未被赋值,默认为nil,调用each方法就会抛出该异常。
相同代码在index页可正常运行,是因为你在ArticlesController的index动作中为该实例变量完成了赋值,但show动作中没有对应的赋值逻辑。
可根据需求选择以下方案修复:
- 方案1:在
show动作中补充赋值逻辑,和index动作里的最新文章查询逻辑保持一致即可,示例代码如下:
def show # 保留你原有查询单篇文章的逻辑 @article = Article.find(params[:id]) # 补充最新文章变量赋值 @latest_articles = Article.order(created_at: :desc).limit(5) end
- 方案2:如果多个页面都需要渲染该侧边栏模块,可以把赋值逻辑抽为公共的前置回调,避免重复编写代码:
class ArticlesController < ApplicationController # 仅在需要渲染侧边栏的动作触发赋值,可根据需求调整范围 before_action :set_latest_articles, only: [:index, :show] # 原有index、show等动作逻辑保持不变 private def set_latest_articles @latest_articles = Article.order(created_at: :desc).limit(5) end end
- 额外容错优化:可以在latest articles局部视图中增加空值判断,避免变量未赋值时直接报错:
<% if @latest_articles&.present? %> <% @latest_articles.each do |article| %> <!-- 原有文章项渲染逻辑 --> <% end %> <% else %> <p>暂无最新文章</p> <% end %>
内容的提问来源于stack exchange,提问作者Ohre Alex Oghenebrorhien
相关产品推荐
相关产品推荐

