I've got two models - Physician
and Patient
. Physician can only give recommendations to patients who have completed the phone number on their account, otherwise the physician should be redirected to the edit patient page. Below is my code:
recommendation_controller.rb new method
def new
authorize Recommendation
@registrant = Registrant.find(params[:registrant_id])
@recommendation = Recommendation.new(patient: @registrant)
end
policies
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
So the question is how to pass @registrant object in to the new?
policy to check if that registrant has a phone number?
I will create custom permission under RegistrantPolicy
to check recommendation allowed or not.
policy:
class RegistrantPolicy < ApplicationPolicy
def recommendation_allowed?
record.phone_number.present?
end
end
and apply it in recommendation_controller.rb
like
def new
authorize Recommendation
@registrant = Registrant.find(params[:registrant_id])
authorize @registrant, :recommendation_allowed?
@recommendation = Recommendation.new(patient: @registrant)
end