Welcome#show中的NoMethodError

时间:2018-09-19 10:27:18

标签: ruby ruby-on-rails-5 nomethoderror

这是我遇到的错误:

error

背景:

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

<% 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,我们将提供任何帮助。

1 个答案:

答案 0 :(得分:2)

您已经定义了@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!更改为complete!,因为没有CoursesUser方法。

所以最终的代码应该是

<% @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 %>