使用Rails 5分配给用户的完整课程和模块

时间:2018-08-22 17:26:03

标签: ruby-on-rails ruby activerecord ruby-on-rails-5 has-and-belongs-to-many

编辑#2

这是课程负责人

class CoursesController < ApplicationController
  layout proc { user_signed_in? ? "dashboard" : "application" }

  before_action :set_course, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:index, :show]
  before_action :authorize_admin, except: [:index, :show, :complete]

  def index
    @courses = Course.all.order(created_at: :asc)
  end

  def show
    course = Course.friendly.find(params[:id])
    @course_modules = course.course_modules.order(created_at: :asc)
  end

  def new
    @course = Course.new
  end

  def edit
  end

  def create
    @course = Course.new(course_params)

    respond_to do |format|
      if @course.save
        format.html { redirect_to courses_path, notice: 'Course was successfully created.' }
        format.json { render :show, status: :created, location: courses_path }
      else
        format.html { render :new }
        format.json { render json: @course.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @course.update(course_params)
        format.html { redirect_to @course, notice: 'Course was successfully updated.' }
        format.json { render :show, status: :ok, location: @course }
      else
        format.html { render :edit }
        format.json { render json: @course.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @course.destroy
    respond_to do |format|
      format.html { redirect_to courses_url, notice: 'Course was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

  def set_course
    @course = Course.friendly.find(params[:id])
  end

  def course_params
    params.require(:course).permit(:title, :summary, :description, :trailer, :price)
  end
end

编辑#1

因此,按照下面的Jagdeep的回答,我现在已经执行以下操作:

course.rb

class Course < ApplicationRecord
  extend FriendlyId
  friendly_id :title, use: :slugged

  has_many :course_modules

  validates :title, :summary, :description, :trailer, :price, presence: true

  def complete?
    self.update_attribute(:complete, true)
  end
end

course_modules_user.rb

class CourseModulesUser < ApplicationRecord
  belongs_to :course_module
  belongs_to :user

  def complete!
    self.update_attribute(:complete, true)
  end
end

courses_user.rb

class CoursesUser < ApplicationRecord
  belongs_to :course
  belongs_to :user
end

user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :confirmable,
         :recoverable, :rememberable, :trackable, :validatable

  has_one_attached :avatar

  has_many :courses_users
  has_many :courses, through: :courses_users

  has_many :course_modules_users
  has_many :course_modules, through: :course_modules_users

  def mark_course_module_complete!(course_module)
    self.course_modules_users
      .where(course_module_id: course_module.id)
      .first
      .complete!
    end

  def after_confirmation
    welcome_email
    super
  end

  protected

  def welcome_email
    UserMailer.welcome_email(self).deliver
  end
end

迁移

class CreateCoursesUsers < ActiveRecord::Migration[5.2]
  def change
    create_table :courses_users do |t|
      t.integer :course_id
      t.integer :user_id
      t.boolean :complete

      t.timestamps
    end
  end
end

class CreateCourseModulesUsers < ActiveRecord::Migration[5.2]
  def change
    create_table :course_modules_users do |t|
      t.integer :course_module_id
      t.integer :user_id
      t.boolean :complete

      t.timestamps
    end
  end
end

但是,我遇到这样的错误

image

原始问题

这是previous question的延续,但是,这会偏离主题,因此这里是一个新主题。

在此之后,我大致得到了我想要开始的工作,这是允许人们标记模块并在所有模块都完整的情况下完成课程。但是,在测试新用户后,模块和课程将标记为已完成(显然,新用户不会在登录时完成课程,也不会在所有模块上完成课程),因此我需要所有用户在标记为已完成和未标记为已完成方面是分开的。

以前,一个名称为@engineersmnky的用户提到过HABTM关系,但是,我以前没有对此进行过处理。

这是到目前为止我设置的方式:

user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :confirmable,
         :recoverable, :rememberable, :trackable, :validatable

  has_one_attached :avatar

  has_many :courses

  def after_confirmation
    welcome_email
    super
  end

  protected

  def welcome_email
    UserMailer.welcome_email(self).deliver
  end
end

course.rb

class Course < ApplicationRecord
  extend FriendlyId
  friendly_id :title, use: :slugged

  has_many :users
  has_many :course_modules

  validates :title, :summary, :description, :trailer, :price, presence: true

  def complete!
    update_attribute(:complete, true)
  end
end

course_module.rb

class CourseModule < ApplicationRecord
  extend FriendlyId
  friendly_id :title, use: :slugged

  belongs_to :course
  has_many :course_exercises

  validates :title, :course_id, presence: true

  scope :completed, -> { where(complete: true) }
  after_save :update_course, if: :complete?

  private

  def update_course
    course.complete! if course.course_modules.all?(&:complete?)
  end
end

如果课程是有条件的courses/index.html.erb

<% if course.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/show.html.erb

<% if course_module.complete? %>
  <i class="fas fa-check text-green float-left mr-1"></i>
  <span class="text-xs mr-2">Completed</span>
<% else %>
  <%= link_to complete_course_module_path(course_module), method: :put do %>
  <i class="fas fa-check text-grey-darkest float-left mr-2"></i>
<% end %>

数据库

课程模块

database

课程

courses

2 个答案:

答案 0 :(得分:1)

  

未定义的方法完成了吗?对于CourseModule:0x000 ..

我将着重于错误并解释其原因。您正在complete?的{​​{1}}上呼叫course_module。但是您在<% if course_module.complete? %>模型中没有一种名为complete?的方法。这就解释了错误触发的原因。

您应该在CourseModule中定义它,以避免出现错误

CourseModule

注意:

如果您愿意尝试其他方法,建议您使用enumsclass CourseModule < ApplicationRecord def complete? #your logic here end end 非常强大,并且可以方便地使用内置方法

例如,您可以使用enumsCourseModel更改为下方

enums

通过这种方式,您可以简单地调用class CourseModule < ApplicationRecord extend FriendlyId friendly_id :title, use: :slugged enum status: [ :completed, :not_completed ] belongs_to :course has_many :course_exercises ....... end ,它根据course_module.completed?的{​​{1}}返回truefalse。要将status的状态更新为course_module,只需调用course_module

答案 1 :(得分:0)

您将需要创建新表 courses_users course_modules_users ,以区分不同用户的课程/课程模块。

从表 courses course_modules 中删除字段complete。我们不想将课程/ course_module标记为全局已完成。有关如何使用迁移操作的信息,请参见this

进一步,如下定义用户与课程/课程模块之间的has_many :through关联:

class User < ApplicationRecord
  has_many :courses_users
  has_many :courses, through: :courses_users

  has_many :course_modules_users
  has_many :course_modules, through: :course_modules_users
end

class Course < ApplicationRecord
  has_many :course_modules
end

class CoursesUser < ApplicationRecord
  # Fields:
  #   :course_id
  #   :user_id
  #   :complete

  belongs_to :course
  belongs_to :user
end

class CourseModule < ApplicationRecord
  belongs_to :course
end

class CourseModulesUser < ApplicationRecord
  # Fields:
  #   :course_module_id
  #   :user_id
  #   :complete

  belongs_to :course_module
  belongs_to :user
end

现在,可以通过以下方式进行查询:

Course.all
 => All courses

Course.find(1).course_modules
 => All course modules of a course

user = User.find(1)
course = Course.find(1)

# Assign `course` to `user`
user.courses_users.create(course_id: course.id)

user.courses
 => [course]

course_module = CourseModule.find(1)

# Assign `course_module` to `user`
user.course_modules_users.create(course_module_id: course_module.id)

user.course_modules
 => [course_module]

现在,要为用户标记课程模块完成,请执行以下操作:

class User < ApplicationRecord
  def mark_course_module_complete!(course_module)
    self.course_modules_users
        .where(course_module_id: course_module.id)
        .first
        .complete!
  end
end

class CourseModulesUser < ApplicationRecord
  def complete!
    self.update_attribute(:complete, true)
  end
end

course_module = CourseModule.find(1)

user.mark_course_module_complete!(course_module)

与课程类似:

class User < ApplicationRecord
  def mark_course_complete!(course)
    self.courses_users
        .where(course_id: course.id)
        .first
        .complete!
  end
end

class CoursesUser < ApplicationRecord
  def complete!
    self.update_attribute(:complete, true)
  end
end

这应该解决您的将课程和课程模块标记为基于用户完成的问题

要使其完全发挥作用,还需要考虑其他事项,我将留给您实施,例如当用户的所有课程模块都完成时,将用户的课程标记为自动完成(是的,您需要再次修复),如果至少一个用户模块未完成,则将用户的课程标记为未完成,等等。

如果您再次遇到问题,SO始终处于打开状态。