ruby-on-rails - 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 %>
解决方案
您的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
推荐阅读
- javascript - 模拟 json 中的文字类型
- java - 如果没有名称或 ID,如何使用 java selenium 选择 iframe
- javascript - 这段代码理论上可以阻止 Node JS 应用程序崩溃吗?
- python - 谁能解释这个 Codewars 代码是如何工作的?
- reactjs - 不变违规:“无标题”尚未注册。在以下情况下可能会发生这种情况: * Metro(本地开发服务器)从错误的文件夹运行
- javascript - 检索所有播放列表视频
- weblogic - 为什么 WebLogic 停止长时间运行的线程而不抛出任何异常?
- image - 将使用什么功能来最大化抖动中的图像?
- docker - 如何将 docker 图像名称传递给我的 GitHub 操作
- php - Docker 容器在 aws ec2 首次运行时停止工作