【问题标题】:Pundit Scoping for Model Ownership through a Join table - Rails 4Pundit 通过连接表确定模型所有权范围 - Rails 4
【发布时间】:2014-12-04 16:03:03
【问题描述】:

我通过一个连接表将用户与给定的公司关联起来,因为我需要能够让每个公司都有大量用户,反之亦然。

class User
  has_many :firm_connections, dependent: :destroy
  has_many :firms, through: :firm_connections
end

class FirmConnection
  belongs_to :user
  belongs_to :firm
end

class Firm
  has_many :firm_connections
  has_many :users, through: :firm_connections
end

我的问题是,当用户点击公司的索引页面时,我如何将其范围限定为仅显示与这些用户相关联的内容?

class FirmPolicy < ApplicationPolicy
  class Scope < Scope
    def resolve
      if user.admin?
        scope.all
      else
        scope.where #only the firms associated with that user
      end
    end
  end

我是否需要在公司级别创建一个接受@user 的范围?或者我可以直接内联吗?我可以一起破解一些东西,但还没有把我的头绕到专家面前,所以任何方向都将不胜感激!

像这样:

def self.associated_with(user)
  all.select { |m| m.users.include?(user) }
end

【问题讨论】:

    标签: mysql ruby-on-rails ruby join pundit


    【解决方案1】:

    这应该适合你

    class Firm
      def index
        @firms = policy_scope(Firm)
      end
    end
    
    class FirmPolicy < ApplicationPolicy
      class Scope < Scope
        def resolve
          if user.admin?
            scope.all
          else
            user.firms #only the firms associated with that user
          end
        end
      end
    end
    

    策略不必总是按照您的想法来称呼它,它只需要返回一些东西(对于范围,几乎总是一个 ActiveRecord::Relation,对于常规,true 或 false)。你可以这样做

    scope.includes(:firm_connections).where(firm_connections: { user_id: user.id })
    

    但这不那么可读(IMO)。

    【讨论】:

      猜你喜欢
      • 2017-01-15
      • 2015-12-08
      • 2017-01-04
      • 1970-01-01
      • 2017-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多