I have two models: User and Employer. Users have one Employer. I am using pundit for authorization. With a has_one relationship how would I authorize the new and create actions? Ideally the user couldn't even go to the form if they have already submitted it.
I could do this in the controller:
def new
unless current_user.employer.present?
@employer = Employer.new
else
flash[:error] = "Record already exists"
redirect_back(fallback_location: current_user)
end
end
But I would prefer to do something in pundit.
class EmployerPolicy < ApplicationPolicy
def create?
# Do I check is the @user has an employer before submission?
end
def new?
# Or do I check if the @user has a record before they get here?
end
end
Any insight would be appreciated. Thank you.
I ended up solving this problem without pundit.
In the User
model I build the default association and child (Employer
) on create. Then in the routes.rb
under the resources for employer I exclude create and new.