简体   繁体   English

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

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

I am currently trying to build a simple learning app with rails and I am facing problems. 我目前正在尝试使用Rails构建一个简单的学习应用,但我遇到了问题。 When a user signs up to a course i try to make a viewed_course record for them so that I can display all the viewed_course on their profile page. 当用户注册一门课程时,我会尝试为他们记录一个“ viewed_course”记录,以便我可以在他们的个人资料页面上显示所有“ viewed_course”。

I can't figure out how to set my different controllers so that it creates the viewed_record when I am on the Course Controller /index. 我无法弄清楚如何设置我的不同控制器,以便当我在“课程控制器/索引”上时它可以创建viewed_record。

How can I modify the course/index view so that it creates a new viewed record for the current signed in user. 如何修改课程/索引视图,以便为当前登录的用户创建新的查看记录。

I am using devise. 我正在使用设计。

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

Thank you so much in advance for helping me out! 提前非常感谢您对我的帮助!

Something like this should do it, this is in courses controller show action (index action should be the list of all courses, show action should be viewing an individual course): 应该这样做,这是在课程控制器中显示动作(索引动作应该是所有课程的列表,显示动作应该是查看单个课程):

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

One gotcha is that this would create a new viewed course every time they viewed the page, you would need some logic to only add each course once. 一个陷阱是,这将在他们每次查看页面时创建一个新的查看课程,您需要一些逻辑才能将每个课程添加一次。

Perhaps something like this: 也许是这样的:

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