Ruby on rails 具有公共/私有访问的Rails模型

Ruby on rails 具有公共/私有访问的Rails模型,ruby-on-rails,database-design,Ruby On Rails,Database Design,我正在使用TodoList模型构建一个应用程序,它既可以是私有的(一个User对多个TodoLists),也可以像公共组项目一样运行(多个Users对多个TodoLists) 我目前有一个布尔类型的列is_shared,它确定TodoList是私有的还是公共的。但是,当我试图处理这两种类型的用户访问权限时,我的控制器变得臃肿 是否最好有两个单独的模型,PrivateTodoList和PublicTodoList,这样我就可以用单独的控制器处理每种类型 编辑:以下是我的ToDolistContro

我正在使用
TodoList
模型构建一个应用程序,它既可以是私有的(一个
User
对多个
TodoList
s),也可以像公共组项目一样运行(多个
User
s对多个
TodoList
s)

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

是否最好有两个单独的模型,
PrivateTodoList
PublicTodoList
,这样我就可以用单独的控制器处理每种类型

编辑:以下是我的ToDolistController的一个片段:

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 !@todolist.is_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
类ToDoListsController
您可以通过模型
TodoList
上的单个表继承(STI)来实现这一点,该表继承具有一列
类型
确定
私有TodoList
公有TodoList
TodoList
的类型决定了模型的私有或公共属性

创建迁移以添加列
type
,以处理两种不同
TodoList
类型的单个表继承

rails g migration add_type_to_todo_lists type:string
TodoList
继承自
ActiveRecord::Base

# app/models/todo_list.rb
class TodoList < ActiveRecord::Base
end
因此,使用此设置,当您执行以下操作时:

  • PublicTodoList.new
    ,创建
    TodoList.new(类型:
    PublicTodoList
  • PrivateTodoList.new
    ,创建
    TodoList.new(类型:
    PrivateTodoList
您可以将它们用作应用程序模型的单独模型,以对关联和业务逻辑进行建模


我发现两种不同型号的手机都存在一个问题,那就是你是否有功能创建一个私人列表,公开列表,反之亦然。在两个单独的表中维护记录时,您会遇到问题。请发布您在控制器中处理权限的方式好吗?这是关于如何使用两个单独模型的一个很好的解释,但我正在寻找一个为什么或为什么不。
# app/models/public_todo_list.rb
class PublicTodoList < TodoList
end

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