欢迎#show 中的 NoMethodError

NoMethodError in Welcome#show

这是我遇到的错误:

背景:

我正在尝试根据操作是否完成来显示按钮。这是我的代码

<% if @courses_user.complete! %>
  <%= link_to "Completed", course, class: "block text-lg w-full text-center text-white px-4 py-2 bg-green hover:bg-green-dark border-2 border-green-dark leading-none no-underline" %>
<% else %>
  <%= link_to "View Modules", course, class: "block text-lg w-full text-center text-grey-dark hover:text-darker px-4 py-2 border-2 border-grey leading-none no-underline hover:border-2 hover:border-grey-dark" %>
<% end %>

在我的 courses_user 模型中,我有

class CoursesUser < ApplicationRecord
  belongs_to :course
  belongs_to :user

  has_many :course_modules_users

  def completed!
    self.update_attributes(complete: true)
  end
end

在 welcomeController 中我有

class WelcomeController < ApplicationController
  def show
    @courses = Course.all.order(created_at: :asc)
    @courses_user = CoursesUser.all
  end
end

但我收到了 NoMethodError,如有任何帮助,我们将不胜感激。

您已定义 @courses_user = CoursesUser.all,因此它是一个 集合 而不是单个对象。而且你不能在集合上调用complete!,错误也是如此。

解法:

遍历 @courses_user 并像这样在每个实例上调用 complete!

<% @courses_user.each do |cu| %>
  <% if cu.complete! %>
    <%= link_to "Completed", course, class: "block text-lg w-full text-center text-white px-4 py-2 bg-green hover:bg-green-dark border-2 border-green-dark leading-none no-underline" %>
  <% else %>
    <%= link_to "View Modules", course, class: "block text-lg w-full text-center text-grey-dark hover:text-darker px-4 py-2 border-2 border-grey leading-none no-underline hover:border-2 hover:border-grey-dark" %>
  <% end %>
<% end %>

注:

为避免另一个潜在错误,您应该将 complete! 更改为 completed!,因为在您的 CoursesUser 模型中没有 complete! 方法。

所以最终的代码是

<% @courses_user.each do |cu| %>
  <% if cu.completed! %>
    <%= link_to "Completed", course, class: "block text-lg w-full text-center text-white px-4 py-2 bg-green hover:bg-green-dark border-2 border-green-dark leading-none no-underline" %>
  <% else %>
    <%= link_to "View Modules", course, class: "block text-lg w-full text-center text-grey-dark hover:text-darker px-4 py-2 border-2 border-grey leading-none no-underline hover:border-2 hover:border-grey-dark" %>
  <% end %>
<% end %>