Rails Pundit 访问参数或对象
Rails Pundit access to the params or object
我有两个模型 - Physician
和 Patient
。医师只能向其帐户中已完成 phone 编号的患者提供建议,否则应将医师重定向至编辑患者页面。下面是我的代码:
recommendation_controller.rb新方法
def new
authorize Recommendation
@registrant = Registrant.find(params[:registrant_id])
@recommendation = Recommendation.new(patient: @registrant)
end
政策
class RecommendationPolicy < ApplicationPolicy
def new?
login.physician?
end
end
class ApplicationPolicy
attr_reader :login, :record
def initialize(login, record)
raise Pundit::NotAuthorizedError, "must be logged in" unless login
@login = login
@record = record
end
end
所以问题是如何将@registrant 对象传递给 new?
策略以检查该注册人是否有 phone 号码?
我将在 RegistrantPolicy
下创建自定义权限以检查是否允许推荐。
政策:
class RegistrantPolicy < ApplicationPolicy
def recommendation_allowed?
record.phone_number.present?
end
end
并在 recommendation_controller.rb
中应用它,例如
def new
authorize Recommendation
@registrant = Registrant.find(params[:registrant_id])
authorize @registrant, :recommendation_allowed?
@recommendation = Recommendation.new(patient: @registrant)
end
我有两个模型 - Physician
和 Patient
。医师只能向其帐户中已完成 phone 编号的患者提供建议,否则应将医师重定向至编辑患者页面。下面是我的代码:
recommendation_controller.rb新方法
def new
authorize Recommendation
@registrant = Registrant.find(params[:registrant_id])
@recommendation = Recommendation.new(patient: @registrant)
end
政策
class RecommendationPolicy < ApplicationPolicy
def new?
login.physician?
end
end
class ApplicationPolicy
attr_reader :login, :record
def initialize(login, record)
raise Pundit::NotAuthorizedError, "must be logged in" unless login
@login = login
@record = record
end
end
所以问题是如何将@registrant 对象传递给 new?
策略以检查该注册人是否有 phone 号码?
我将在 RegistrantPolicy
下创建自定义权限以检查是否允许推荐。
政策:
class RegistrantPolicy < ApplicationPolicy
def recommendation_allowed?
record.phone_number.present?
end
end
并在 recommendation_controller.rb
中应用它,例如
def new
authorize Recommendation
@registrant = Registrant.find(params[:registrant_id])
authorize @registrant, :recommendation_allowed?
@recommendation = Recommendation.new(patient: @registrant)
end