我希望在rails应用程序中分享用户之间的课程。用户A已经创建了一些课程,并希望与用户B& C.用户A创建课程,添加用户B& C到课程,他们现在可以看到课程。我的问题是如何让共享课程出现在用户B& C共享页面?每节课都属于笔记本。
notebook.rb
belongs_to :user
has_many :lessons, :dependent => :destroy
lesson.rb
belongs_to :notebook
has_many :shareships
has_many :users, through: :shareships, dependent: :destroy
attr_reader :user_tokens
accepts_nested_attributes_for :shareships, :reject_if => lambda { |a| a[:user_ids].blank? }
scope :shared, lambda { where('shared_ids = ?')
user.rb
has_many :notebooks, dependent: :destroy
shareship.rb
belongs_to :lesson
belongs_to :user
lessons_controller.rb
class LessonsController < ApplicationController
before_filter :authorize, :find_notebook
load_and_authorize_resource :through => :notebook, :except => [:public]
respond_to :html, :js, :json
def create
@lesson = @notebook.lessons.build(params[:lesson])
@lesson.user_id = current_user.id
flash[:notice] = 'lesson Added!.' if @lesson.save
respond_with(@lesson, :location => notebook_lessons_path)
end
def shared
@user = current_user
@shared = @notebook.lessons
end
end
我已经设置了用户和课程之间的多对多关联,因此用户可以将其他用户添加到课程中,但我正在尝试找出如何列出共享用户的课程。任何想法我怎么能让这个工作?我无法设置它和我的控制器和视图。
答案 0 :(得分:1)
我会做这样的事情
<强> notebook.rb 强>
has_many :lessons
belongs_to :user
<强> lesson.rb 强>
belongs_to :notebook
has_many :shareships
has_many :users, through: :shareships, dependent: :destroy # shared users of this lesson, not the owner
<强> user.rb 强>
has_many :notebook # the user will go through the notebook to get the lesson he owns
has_many :shareships
has_many :lessons, through: :shareships, dependent: :destroy # this would be only the shared lessons he has access to
<强> shareship.rb 强>
belongs_to :lesson
belongs_to :user
用户可以通过
访问他拥有的课程/:user_id/notebooks/:notebook_id/lesson/:lesson_id
# lessons = user.notebooks[:notebook_id].lessons
他可以通过
访问与他分享的课程/:user_id/shared_lessons/:lesson_id
# shared_lessons = user.lessons
用户无法直接访问他所拥有的课程,他需要浏览他的笔记本。但他可以直接访问共享课程。
你觉得怎么样?