我正在尝试制作" next"按钮,应生成Viewed_lesson(user_id,lesson_id,boolean:true),然后重定向到下一课。目的是进行跟踪进度以显示用户在课程上的进度。
我的模特:
class Course
has_many :lessons
end
class Lesson
#fields: course_id
belongs_to :course
end
class User
has_many :viewed_lessons
has_many :viewed_courses
end
class ViewedLesson
#fields: user_id, lesson_id, completed(boolean)
belongs_to :user
belongs_to :lesson
end
class ViewedCourse
#fields: user_id, course_id, completed(boolean)
belongs_to :user
belongs_to :course
end
seen_lesson控制器的创建操作应该是什么样的?
只需要一个创建方法。 按钮/窗体在视图中的外观如何?该按钮位于讲座/ id / lesson / id
中提前感谢您的帮助!
答案 0 :(得分:1)
我会说你的设计听起来有点偏。在轨道中,模型和控制器之间并不总是存在1:1的混乱关系。
首先,我会重命名这些模型UserLesson
和UserCouse
。它使关系变得非常明显,并且ViewedLesson
发臭,因为它暗示某种状态。
在Rails中,模型和控制器之间的1:1关系并不总是最佳解决方案。有时只使用标准的crud动词可能不会削减它。
想象一下以下情景:
POST /user/1/lessons
是否表示用户已完成课程?
或者这是否意味着用户刚开始上课?
相反,您可能希望进行如下设计:
# config/routes.rb
resources :lessons # Used by admins to CRUD the curriculum.
resources :users
resources :lessons, controller: `users/lessons` do
member do
post :complete
end
end
end
# app/controllers/users/lessons_controller.rb
module Users
class LessonsController
before_action :set_lesson, only: [:show, :update, :complete]
# ...
# Enroll user in a lession
# POST /users/:user_id/lessons/:id
def create
@user_lesson = UserLesson.create(lesson: params[:id], user: params[:user_id])
end
# POST /users/:user_id/lessons/:id/complete
def complete
# @todo check if user has completed all steps...
end
# Save user progress when they reach certain milestones
def update
# @todo update user_lesson
end
def set_lesson
@lesson = Lession.find(params[:id])
end
def set_user_lesson
@user_lesson = UserLesson.find_by(user: params[:user_id], lession_id: params[:id])
end
end
end
另一种选择是,如果您不想在users
下嵌套路线:
resources :lessions, controller: 'user_lessions' do
member do
post :complete
end
end
# or
resources :courses, controller: 'user_courses' do
resources :lessions, controller: 'user_lessions' do
member do
post :complete
end
end
end
namespace :admin do
resources :lessions # used to crud the corriculum
end
答案 1 :(得分:0)
它应如下所示:
class ViewedLessonsController < ApplicationController
before_filter :set_user_and_lesson
def create
@viewed_lesson = ViewLession.new(user_id: @user.id, lession_id: @lesson.id, completed: true)
if @viewed_lesson.save
# redirect_to appropriate location
else
# take the appropriate action
end
end
end
在ApplicationController
课程中,您可以:
def set_user_and_lesson
@user = User.find_by_id(params[:user_id])
@lesson = Lesson.find_by_id(params[:lesson_id])
end
您还需要为其定义路线,并且请记住,您还需要为ViewedLesson
和ViewedCourse
设置模型。