具有公共/私人访问权限的Rails模型

时间:2017-06-15 01:17:10

标签: ruby-on-rails database-design

我正在使用TodoList模型构建应用,而不是私有(一个User到多个TodoList),或者表现得像一个公共群组项目(很多User到多个TodoList s。。

我目前有一个boolean类型的列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 !@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

1 个答案:

答案 0 :(得分:0)

您可以在模型TodoList上使用单个表继承(STI)执行此操作,并使用列type确定PrivateTodoListPublicTodoListTodoList的类型决定了模型的私有属性或公共属性。

创建迁移以添加列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

继承的模型(这些模型由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