首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails从多到多关联访问信息。

Rails从多到多关联访问信息。
EN

Stack Overflow用户
提问于 2012-08-13 00:58:16
回答 1查看 96关注 0票数 0

我希望在rails应用程序中的用户之间分享经验教训。用户A已经创建了一些课程,并希望与用户B& C共享它。用户A创建一个课程,将用户B&C添加到该课程中,他们现在可以看到该课程了。我的问题是如何让共享的课程出现在用户的B&C共享页面中?每堂课都属于一个笔记本。

notebook.rb

代码语言:javascript
复制
belongs_to :user
has_many :lessons, :dependent => :destroy

lesson.rb

代码语言:javascript
复制
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

代码语言:javascript
复制
has_many :notebooks, dependent: :destroy 

shareship.rb

代码语言:javascript
复制
belongs_to :lesson
belongs_to :user

lessons_controller.rb

代码语言:javascript
复制
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

我已经设置了用户和课程之间的许多关联,这样用户就可以将其他用户添加到一个课程中,但是我正在努力弄清楚如何列出共享用户的经验教训。有什么办法能让这件事起作用吗?我设置它和我的控制器和视图有困难。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-08-15 00:35:21

我会做这样的事

notebook.rb

代码语言:javascript
复制
has_many :lessons
belongs_to :user

lesson.rb

代码语言:javascript
复制
belongs_to :notebook
has_many :shareships
has_many :users, through: :shareships, dependent: :destroy # shared users of this lesson, not the owner

user.rb

代码语言:javascript
复制
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

代码语言:javascript
复制
belongs_to :lesson
belongs_to :user

用户可以访问他所拥有的课程。

代码语言:javascript
复制
/:user_id/notebooks/:notebook_id/lesson/:lesson_id 
# lessons = user.notebooks[:notebook_id].lessons

他可以通过以下途径获得与他分享的课程

代码语言:javascript
复制
/:user_id/shared_lessons/:lesson_id
# shared_lessons = user.lessons

用户无法直接获取他所拥有的课程,他需要查看他的笔记本。但他可以直接学到分享的课程。

你觉得呢?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11927106

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档