ruby-on-railsruby-on-rails-4modelrelationvalidates-uniqueness-of

Validates uniqueness record per user per lesson // Rails 4


Problem: I want to have only 1 UserLesson per User per Video because I'm building a tracking system (progress system) User shall be able to see how many lessons are remaining lesson/total lesson and also when marked as completed shall add css

I send the data from the view to the controller:

 <%= 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' %>

The controller receives data and launch the create method

 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

Here is the model relationship

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

My guess was to validates uniqueness of user-lesson per user and lesson. However can't seem to work got the error message.


Solution

  • Add this validation to your model to ensure uniqueness by user scope:

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