1

问题:我希望每个视频每个用户只有 1 个 UserLesson, 因为我正在构建一个跟踪系统(进度系统)用户应该能够看到剩余的课程/总课程还有多少课,并且当标记为已完成时应该添加 css

我将数据从视图发送到控制器:

 <%= link_to 'Mark as completed', user_lessons_path(@user_lesson, user_lesson: {user_id: current_user.id, lesson_id: @lesson.id}), :method => :post, class: 'btn btn-primary-big' %>

控制器接收数据并启动创建方法

 class UserLessonsController < ApplicationController
  before_filter :set_user_and_lesson

  def show
  end 

  def create
    @user_lesson = UserLesson.create(user_lesson_params)
    if @user_lesson.save
      flash[:success] = "You rock! Keep up ;)"
        redirect_to(:back)
    else
     flash[:success] = "You have already completed this lesson"
     redirect_to(:back)
   end
 end

  private

   def user_lesson_params 
      params.require(:user_lesson).permit(:user_id, :lesson_id, :completed)
end
end

这是模型关系

class UserLesson < ActiveRecord::Base
    belongs_to :user 
    belongs_to :lesson
    # validates_uniqueness_of :user_lesson, :scope => [:user, :lesson]
    end

 class Lesson < ActiveRecord::Base
    has_one :lecture, through: :chapter
   belongs_to :chapter 
 end

class User < ActiveRecord::Base
   has_many :enrollments
   has_many :user_lessons
   has_many :lectures, through: :enrollments
   accepts_nested_attributes_for :enrollments
 end

class Enrollment < ActiveRecord::Base
    belongs_to :user 
    belongs_to :lecture
    validates :lecture, uniqueness: { scope: :user, message: "should happen once per user" }
end

class Lecture < ActiveRecord::Base
    belongs_to :category
    has_many :lessons, through: :chapters, dependent: :destroy 
    has_many :chapters
    belongs_to :teacher

    # For course user relationship 
    has_many :enrollments 
    has_many :users, through: :enrollments

    accepts_nested_attributes_for :enrollments
    accepts_nested_attributes_for :chapters
 end

class Chapter < ActiveRecord::Base
    has_many :lessons
    belongs_to :lecture
    accepts_nested_attributes_for :lessons
end

我的猜测是验证每个用户和课程的用户课程的唯一性。但是似乎无法工作得到错误消息。

4

1 回答 1

2

将此验证添加到您的模型以确保用户范围的唯一性:

 validates :lesson_id, :uniqueness => {:scope=>:user_id}
于 2015-08-25T14:33:55.360 回答