I've modified one of my Goal.rb model to only allow one field to be edited by admins. This model and all actions within it was working prior to this update. This update also works for the edit action, but on the create action returns
Pundit::NotDefinedError in GoalsController#create
unable to find policy of nil
I'm hoping this is just a syntax error, I don't understand why it's not working as no model/policy file names have been changed, only the params and policy settings (which work for the edit action)
I thought it might be because I'm calling the policy on @goal while creating it, but how else would I check permissions there, if not this way?
goals_controller.rb:
def create
@goal = Goal.new(permitted_attributes(@goal))
#stuff
authorize @goal
respond_to do |format|
if @goal.save
# format.json { render :show, status: :created, location: @goal }
else
# format.json { render json: @goal.errors, status: :unprocessable_entity }
end
end
end
def update
authorize @goal
update_params = permitted_attributes(@goal)
#
end
respond_to do |format|
if @goal.update(update_params)
# format.json { render :show, status: :ok, location: @goal }
else
# format.json { render json: @goal.errors, status: :unprocessable_entity }
end
end
end
I just realised, you can call permissions on a new class. I had read this three times, but only after posting the question did it click.
I was trying to check the allowed params of @goal, which didn't yet exist and was showing a nil policy, but with Pundit you can run a check against the allowed params of a Class, in this case:
@goal = Goal.new(permitted_attributes(Goal))