首页 > 解决方案 > true:TrueClass 的未定义方法“课程”

问题描述

当且仅当用户完成任务的必修课程时,我希望用户能够查看任务的提交按钮。现在,我在我的 tasks/show.html.erb 页面中添加了一条 current_user.complete(@task.courses.all?) 行,它应该只允许用户在完成任务的课程后查看提交按钮。但是这一行在 def 完整用户方法中抛出了一个错误,说方法课程未定义为 true:TrueClass。

任务模型:

has_many :submissions
has_and_belongs_to_many :courses

提交模型:

belongs_to :user
belongs_to :task

课程模式:

has_many :lessons, dependent: :destroy
has_many :users, through: :enrolments
has_and_belongs_to_many :tasks, optional: true

课程模式:

belongs_to :course
has_many :views
has_many :users, through: :views

用户模型:

has_many :courses, through: :enrolments
has_many :submissions
has_many :views
has_many :lessons, through: :views


def view(lesson)
  lessons << lesson
end

def viewed?(lesson)
  lessons.include?(lesson)
end

def complete(course)
  lessons.where(course: course).ids.sort == course.lessons.ids.sort
end

任务/Show.html.erb:

<% if current_user.complete(@task.courses.all?)%>
  <%= link_to "Submit", new_task_submission_path(@task), class: "btn btn-primary" %>
<% end %>

标签: ruby-on-railsruby

解决方案


您的complete方法需要course作为参数,并尝试调用course.lessons它。

你在打电话

current_user.complete(@task.courses.all?)

这意味着您将布尔值传递给complete而不是课程。

也许你的意思是:

@task.courses.all? { |course| current_user.complete(course) }

Aleksei Matiushkin 建议使用以下内容会更有效:

current_user.joins(:courses).joins(:lessons).where(complete: false).count == 0

推荐阅读