true的未定义方法“课程”:TrueClass

时间:2019-06-02 09:04:18

标签: ruby-on-rails ruby

我希望用户只有在完成了任务的必修课程后,才能查看任务的提交按钮。现在,我在task / show.html.erb页面上添加了current_user.complete(@ task.courses.all?)这行,只允许用户在完成任务课程后查看“提交”按钮。但是这一行在def complete用户方法上引发了一个错误,说该方法课程未定义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

Task / Show.html.erb:

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

1 个答案:

答案 0 :(得分:1)

您的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