2017-06-15 84 views
0

我建立一个应用程序与TodoList模型,模型相比可以是私有的(一个User许多TodoList S),或像一个公共组项目(许多User s到许多TodoList小号)。Rails的公共/私有访问

我目前有一个布尔类型的列is_shared,它确定TodoList是私人的还是公共的。但是,当我尝试处理这两种类型的用户访问权限时,我的控制器变得臃肿。

有两个独立的模型PrivateTodoListPublicTodoList会更好吗,所以我可以使用单独的控制器处理每种类型?

编辑:这是我的TodoListsController的一个片段:

class TodosListsController < ApplicationController 
    before_action :authenticate_user 
    before_action :set_todolist, only: [:show, :update, :destroy] 
    before_action :authorized?, only: [:show, :update, :destroy] 
    before_action :member?, only: :show 
    before_action :admin?, only: :update 

    # resourceful actions... 

    private 

    def set_todolist 
    @todolist = TodoList.find(params[:id]) 
    end 

    def authorized? 
    if [email protected]_shared && @todolist.creator.id != current_user.id 
     json_response('Not authorized to view or edit this Todo List', :unauthorized) 
    end 
    end 

    def member? 
    if @todolist.is_shared 
     unless @todolist.members.find_by_id(current_user.id) || 
      @todolist.admins.find_by_id(current_user.id) 
     json_response('You are not a member of this Todo List', :unauthorized) 
     end 
    end 
    end 

    def admin? 
    if @todolist.is_shared 
     unless @todolist.admins.find_by_id(current_user.id) 
     json_response('You are not an admin of this Todo List', :unauthorized) 
     end 
    end 
    end 
end 
+0

一个问题我有两个单独的机型看到的是,如果你有功能拨打私人列表,公共反之亦然。您将在两张独立的表中保持记录时遇到麻烦。 – Pramod

+0

请问您是否在控制器中处理权限的方式? – Bustikiller

回答

0

您可以用单个表的传承(STI)的模型TodoList以确定PrivateTodoListPublicTodoListtype做到这一点。 TodoList的类型决定了您的模型的私人或公共财产。

创建迁移添加列type处理两个不同TodoList类型

TodoList继承的单表-传承从ActiveRecord::Base

# app/models/todo_list.rb 
class TodoList < ActiveRecord::Base 
end 

遗传模型(这些由type柱区分在todo_lists表中)继承自TodoList类。

# app/models/public_todo_list.rb 
class PublicTodoList < TodoList 
end 

# app/models/private_todo_list.rb 
class PrivateTodoList < TodoList 
end 

所以,用这种设置,当你这样做:

  • PublicTodoList.new,创建TodoList.new(type: PublicTodoList )
  • PrivateTodoList.new,创建TodoList.new(type: PrivateTodoList )

您可以将它们作为单独的模型为您的应用程序的模型到模型屁股事件和业务逻辑。

more info on STI

+0

这是对_how_使用两个独立模型的一个很好的解释,但我正在寻找_why_或_why not_。 – jim