与专家有 has_one 关系
Pundit with has_one relationship
我有两个模型:用户和雇主。用户有一个雇主。我正在使用权威人士进行授权。有了 has_one 关系,我将如何授权新操作和创建操作?理想情况下,如果用户已经提交了表单,他们甚至无法访问该表单。
我可以在控制器中这样做:
def new
unless current_user.employer.present?
@employer = Employer.new
else
flash[:error] = "Record already exists"
redirect_back(fallback_location: current_user)
end
end
但我更愿意在专家中做点什么。
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
如有任何见解,我们将不胜感激。谢谢。
我最终在没有专家的情况下解决了这个问题。
在 User
模型中,我在创建时构建默认关联和子 (Employer
)。然后在雇主资源下的 routes.rb
我排除了 create 和 new。
我有两个模型:用户和雇主。用户有一个雇主。我正在使用权威人士进行授权。有了 has_one 关系,我将如何授权新操作和创建操作?理想情况下,如果用户已经提交了表单,他们甚至无法访问该表单。
我可以在控制器中这样做:
def new
unless current_user.employer.present?
@employer = Employer.new
else
flash[:error] = "Record already exists"
redirect_back(fallback_location: current_user)
end
end
但我更愿意在专家中做点什么。
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
如有任何见解,我们将不胜感激。谢谢。
我最终在没有专家的情况下解决了这个问题。
在 User
模型中,我在创建时构建默认关联和子 (Employer
)。然后在雇主资源下的 routes.rb
我排除了 create 和 new。