验证每个用户每课的唯一性记录// Rails 4

时间:2015-08-24 12:10:37

标签: ruby-on-rails ruby-on-rails-4 model relation validates-uniqueness-of

问题:我希望每个用户每个视频只有一个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' %>

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

 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

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

1 个答案:

答案 0 :(得分:1)

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

 validates :lesson_id, :uniqueness => {:scope=>:user_id}