Задача: Я хочу иметь только 1 UserLesson на пользователя на видео , потому что я строю систему отслеживания (система прогресса) Пользователь должен уметь видеть, сколько уроки оставшихся уроков/общий урок, а также когда помечена как завершенная добавим CSSПодтверждает запись уникальности для каждого пользователя за урок // Rails 4
я отправить данные с точки зрения к контроллеру:
<%= 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
Мое предположение было подтверждает уникальность пользовательского урока для каждого пользователя и урока. Однако, похоже, не получается получить сообщение об ошибке.
Что такое сообщение об ошибке? – usmanali
Не определено user_lesson в контроллере – AdrienNhm
Вы можете вставить всю строку? – usmanali