0
問題:我希望每個用戶只有每位用戶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
控制器 – AdrienNhm
中未定義的user_lesson可以粘貼整行嗎? – usmanali