如何在Squeel中加入具有条件的子查询

时间:2012-07-07 06:15:57

标签: join subquery squeel

序言

我接受了Squeel - 享受每一步!非常感谢你分享,Ernie Miller!

我正在开发ruby 1.9.2和Squeel 1.0.2以及Rails 3.2.5

(我承认完全重组了这个问题 - 希望增加可读性并提高我获得答案的机会)<:)

用例

我希望(超级)用户能够像这样分配授权和权限

  • user_group应该能够拥有多个授权
  • 授权应该能够拥有多个权限
  • 权限应该能够控制对(操纵)数据的访问
    • 通过控制器(请求路径)
    • 关于Class
    • 的实例
    • 在任何特定实例上

ACL系统应该 lazy - 即如果没有给出角色/授权,用户显然根本不关心ACL。

迁移

我在用例中确定了角色和(多态)可角色实体,因此我有

一个与众不同的角色

create_table :roles do |t|
  t.references :ox
  t.string :name
  t.boolean :active, default: true
  t.timestamps
end

和一个更具描述性的角色

create_table :roleables do |t|
  t.references :ox
  t.references :role
  t.references :roleable, polymorphic: true
  t.string :authorization
  t.string :controller
  t.boolean :active, default: true
  t.timestamps
end

系统有一个泛型类 - AbstractActionBase - 它继承自ActiveRecord:Base,所有类都继承自(允许我在一个地方添加系统范围的属性和方法)

所以 - 部分 - 我的AbstractActionBase看起来像

class AbstractActionBase < ActiveRecord::Base
  self.abstract_class=true

  require 'tempfile'

  belongs_to :ox

  has_many :roleables, as: :roleable

  attr_accessible :ox_id

  validates_presence_of :ox_id

  #
  # all models inheriting from this will have versions
  has_paper_trail
  #
  #

  # 
  # Class method to providing for index SELECT's being married with roleables (permissions)
  # used from abstraction_actions_controller where build_collection calls this method 
  # the result 'should' be an ActiveRelation - used for the Kamanari 'result' call to readying pagination
  #
  def self.with_authorizations    

    # 
    # SELECT * FROM any_table at
    # left join (
    #     select r.roleable_id, r.roleable_type, group_concat( r.authorization )
    #   from roleables r
    #   where r.authorization is not null
    #   and r.roleable_id=at.id
    #   and r.roleable_type=at.base_class
    #   and r.role_id not in (1,2,3) <--- ID's are current_user.roles
    # ) rm on rm.roleable_id=at.id and rm.roleable_type=at.base_class
    #
    # which will provide for this:
    #
    # |.......| last column in table 'at' | roleable_id | roleable_type | authorizations |
    # |.......| some value                | 1           | 'UserGroup'   | 'insert,create'|
    # |.......| yet another value         | 92          | 'UserGroup'   | 'read'         |
    #
    #
    self.where{ active==true }
  end

  # compile a collection of records - regard search using Ransack
  def base.collection( params, resource_set )
    #
    # kaminari (and continous scrolling)
    #
    params[:page] ||= 1
    params[:per_page] ||= self.per_page
    params[:o] ||= self.resource_order_by
    distinct = params[:distinct].nil? ? false : params[:distinct].to_i.zero?
    resource_set = (resource_set.respond_to?( "result")) ? resource_set.result(:distinct => distinct) : resource_set
    (resource_set.respond_to?( "page")) ? resource_set.order(params[:o]).page( params[:page] ).per( params[:per_page] ) : resource_set.order(params[:o])
  end
end

Role类的一部分看起来像这样

class Role < AbstractActionBase

  has_many :roleables

  scope :active, where{ active.eq true }

  #
  # what does this role allow
  def permissions
    roleables.permissions.scoped
  end

  # 
  # to whom does this role allow
  def authorizations
    roleables.authorizations.scoped
  end

  # returns true if the roleables (permissions) authorizes the options
  # options are { controller: "", action: "", record: Instance, is_class: boolean }
  def authorizes?( options={} )
    coll = permissions
    coll = coll.on_action(options.delete(:action)) if options.keys.include? :action
    coll = coll.on_entity( options.delete(:record), options.delete(:is_class) || false ) if options.keys.include? :record
    coll = coll.on_controller(options.delete(:controller)) if options.keys.include? :controller
    (coll.count>0) === true
  end
end

Roleable类看起来像这样

class Roleable  < AbstractActionBase
  belongs_to :role
  belongs_to :roleable, polymorphic: true

  # roleables authorizes users through user_groups
  # (in which case the authorization is "-")
  # providing them permissions on controllers, actions and instances
  scope :authorizations, where{ authorization == nil }
  scope :permissions, where{ authorization != nil }

  # using Squeel, find roleables on a particular controller or any controller
  def self.on_controller(ctrl)
    where{ (controller==ctrl) | (controller==nil) }
  end

  # using Squeel, find roleables on a particular authorization or allowed 'all'
  def self.on_action(action)
    where{ (authorization=~ "%#{action}%") | (authorization=="all") }
  end

  # using Squeel, find roleables on a particular instance/record or class
  def self.on_entity(entity, is_class=false)
    if is_class
      where{ ((roleable_type==entity.base_class.to_s ) & ( roleable_id==nil)) | ((roleable_type==nil) & (roleable_id==nil)) }
    else
      where{ ((roleable_type==entity.class.to_s ) & ( roleable_id==entity.id)) | ((roleable_type==nil) & (roleable_id==nil)) }
    end
  end
end

逻辑

创建

这允许我授权 - 将角色分配给某人/某事 - 在这种情况下授权字符串为nil,如

  

为user_group 销售分配了角色销售   使用Roleable.create({role:@sales,roleable:@user_group})

同时我可以做权限 - 描述任何角色的细节 - 比如

  

角色销售具有索引创建编辑删除权限   在带有

的OrderHead和OrderDetail表上
  • Roleable.create({role:@sales,authorization:“index,create,edit,delete”,roleable:@user_group,controller:“order_heads”})
  • Roleable.create({role:@sales,authorization:“index,create,edit,delete”,roleable:@user_group,controller:“order_details”})

这些'细节'可以像空灵一样

  

Roleable.create({role:@sales,authorization:“index”})

有点真实

  

Roleable.create({role:@sales,authorization:“index”,roleable_type:'OrderHead'})

或非常表达

  

Roleable.create({role:@sales,authorization:“index”,roleable:OrderHead.first})

选择

大多数每个控制器都继承自AbstractActionsController,其中定义了索引(和其他操作)。该控制器自己继承自InheritedResources:像这样的基础

class AbstractActionsController < InheritedResources::Base # < ApplicationController

  append_view_path ViewTemplate::Resolver.instance

  respond_to :html, :xml, :json, :js, :pdf

  belongs_to :ox, :optional => true

  before_filter :authorize!
  before_filter :authenticate!
  before_filter :warn_unless_confirmed!
  before_filter :fix_money_params, :only => [:create,:update]

  # GET /collection - printers
  def index

    # session[:params] = params
    #
    # preparing for Ransack
    unless params[:q].nil?
      params[:q]= { :"#{params[:q_fields]}" => params[:q] }
    end

    super do |format|
      format.html 
      format.js { render layout: false }
      format.pdf{ render :pdf => generate_pdf(false) and return }
      format.xml { render layout: false }
      format.json do
        # field lookup request?
        unless params[:lookup].nil?
          render layout: false, :json => collection.map(&:select_mapping)
        else
          render json: collection.map { |p| view_context.grow_mustache_for_index(p, collection, (parent? ? collection : resource_class.order(:id)), @selected ) }
        end
      end
    end
  end


  # the collection method on inherited_resources 
  # gets overloaded with Ransack search and Kaminari pagination (on the model)
  def collection
    # @collection ||= build_collection
    # TODO - test whether caching the collection is possible
    build_collection
  end

  def build_collection
    unless params[:belongs].nil?
      # debugger
      parent = params[:belongs].constantize.find(params[:belongs_id])
      @selected = parent.nil? ? [] : parent.send( rewrite_association(params[:assoc],parent) )
      @search_resource = core_entity(params[:assoc].constantize)
      @search_resource = @search_resource.search(params[:q]) unless params[:q].nil?
    else
      @search_resource = rewrite_end_of_association_chain(resource_class)
      @search_resource = core_entity(@search_resource)
      @search_resource = @search_resource.search(params[:q]) unless params[:q].nil?
    end
    # authorize rows
    @search_resource = @search_resource.with_authorizations                 # left joins roleables coalescing a "authorization" field from roles ID's not owned by current_user through his user_groups
    @resources ||= resource_class.collection( params, @search_resource )
  end

end

挑战

提出一个简短问题&lt ;:)

的故事很长

如何编写with_authorizations方法来返回ActiveRelation(最好使用Squeel)

2 个答案:

答案 0 :(得分:1)

沃尔特,

你可能会使这比必要的更复杂。如果我正确地阅读此内容,则子查询的主要目的是获得结果中可用授权的连锁列表。如果是这种情况,您可以简单地通过eager_load授权并通过Role模型公开其名称,该模型为您进行连接。这具有与MySQL以外的DB兼容的次要优势。

答案 1 :(得分:0)

就像我说的 - 最好使用Squeel:)

事实证明(从马口可以这么说)加入是在Squeel-county的协会;)

那么 - 该怎么办?好吧,我用我的SQL-to-ActiveRecord套索摆动了最后一次 tour de SO ,并且瞧瞧!有人提出了一个很好的问题 - 而且有更大的答案!完美。

在一些短暂的几乎发烧的时刻,我用所描述的技术砍掉了 - 和Heureka !!

之前,我添加了一个pastiebin以帮助可能的“回答” - 所以我已将结果添加到pastiebin - 但简而言之就是这样:

Model.select("something").joins("to your hearts contend")

干杯, 瓦尔特