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

Ruby on Rails访问myarticles页面报NoMethodError错误求助

问题产生原因

  1. 控制器ArticlesController的myarticles方法中,仅定义了复数实例变量@articles,未定义视图中调用的单数实例变量@article,导致视图读取@article.title时变量为nil,触发空类方法不存在报错。
  2. 逻辑定位不匹配:myarticles的设计定位是用户文章列表页,你直接复用了单篇文章详情页show.html.erb的代码,详情页依赖单条@article记录,和列表页的多记录场景完全不兼容。

解决方法

方案1:临时调试,保留单篇展示逻辑

如果只是临时测试,希望页面先跑通复用现有单篇展示代码,直接在myarticles方法中给@article赋值即可:

def myarticles
  # 示例:取最新的一篇文章用于测试
  @article = Article.order(created_at: :desc).first
  # 若要指定ID可改为 @article = Article.find(文章ID)
end

方案2:符合定位,实现「我的文章」列表功能

如果要实现myarticles的原本设计功能(展示当前登录用户的所有文章),需要同时修改控制器和视图代码:

第一步:修改控制器逻辑

首先要把myarticles加入登录校验范围,然后仅查询当前用户的文章:

# 顶部的before_action修改,加入myarticles的登录校验
before_action :authenticate_user!, except: [:index, :show ]

# 修改myarticles方法
def myarticles
  @articles = current_user.articles.order(created_at: :desc)
end

第二步:修改视图代码,遍历输出文章列表

将myarticles.html.erb改为遍历@articles的逻辑,示例代码如下:

<p id="notice"><%= notice %></p>

<div style="justify-content: center;display: flex;" >
  <div style="max-width:680px;width: 100%;" >
    <br>
    <h1>我的文章</h1>
    <% @articles.each do |article| %>
      <div class="mb-5 pb-3 border-bottom">
        <h2>
          <%= link_to article.title, article %>
        </h2>
        <p class="text-muted"><%= article.description %></p>
        <% if article.image.attached? %>
          <p style="flex-direction: column;display: flex;" >
            <%= image_tag article.image ,class:"img-fluid", style: "max-height: 300px; object-fit: cover; max-width: 100%;" %>
          </p>
        <% end %>
        <p><%= truncate(article.content, length: 200) %></p>
        <div>
          <%= link_to '查看详情', article, class: "btn btn-secondary me-2" %>
          <%= link_to '编辑', edit_article_path(article), class: "btn btn-secondary me-2" %>
        </div>
      </div>
    <% end %>
    <br>
    <%= link_to '返回文章首页', articles_path, class: "btn btn-secondary" %>
  </div>
</div>

额外潜藏问题修复

你代码中存在另一处关联调用错误:如果User和Article是一对多关联(User has_many :articles),则current_user.article.build需要改为current_user.articles.build,否则创建文章时也会触发方法不存在报错。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:24:00