簡體   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