这是我得到的错误:
背景:
我试图根据动作是否完成显示一个按钮。这是我的代码
<% 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!
,因为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 %>