繁体   English   中英

Rails 4如何为用户(控制器,视图,模型)注册课程

[英]Rails 4 how to make enrolment to a course for users (controller, view, model)

我目前正在尝试使用Rails构建一个简单的学习应用,但我遇到了问题。 当用户注册一门课程时,我会尝试为他们记录一个“ viewed_course”记录,以便我可以在他们的个人资料页面上显示所有“ viewed_course”。

我无法弄清楚如何设置我的不同控制器,以便当我在“课程控制器/索引”上时它可以创建viewed_record。

如何修改课程/索引视图,以便为当前登录的用户创建新的查看记录。

我正在使用设计。

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

提前非常感谢您对我的帮助!

应该这样做,这是在课程控制器中显示动作(索引动作应该是所有课程的列表,显示动作应该是查看单个课程):

class CoursesController < ApplicationController
  def index
    @courses = Course.all
  end

  def show
    @course = Course.find(params[:id])
    current_user.viewed_courses.create(course: @course)
  end  
end

一个陷阱是,这将在他们每次查看页面时创建一个新的查看课程,您需要一些逻辑才能将每个课程添加一次。

也许是这样的:

def show
  @course = Course.find(params[:id])
  current_user.viewed_courses.create(course: @course) unless ViewedCourse.exists?(user_id: current_user.id, course_id: @course.id)
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM