我正在使用权威人士在 Rails 应用程序中进行授权。对于某些模型,我想要属性级授权。例如,普通用户可以更改他的电话号码,但不能将他的状态设置为“管理员”。
根据 the Pundit docs 中的建议, 我正在使用 permitted_attributes
为了这。
我现在想在 View 中访问这些属性,以决定在表单中显示或启用哪些字段。有没有一种(优雅的)方法可以做到这一点,而无需基本上重复那里的授权字段?
最佳答案
首先,您可能想在 ApplicationPolicy
中添加一些不错的快捷方式。这使您可以检查是否允许使用属性:
class ApplicationPolicy
#...
def permits_attributes?(*attrs)
attrs.keep_if({|a| permits_attribute?(a) }).any?
end
def permits_attribute?(attr)
permitted_attributes.include?(attr)
end
# ...
end
然后,您可以创建自定义表单构建器(或扩展表单构建器的模块):
class MyFormBuilder < ActionView::Helpers::FormBuilder
def can_fill_in?(attr)
yield if @template.policy(object).permits_attribute?(attr)
end
end
<%= form_for(@project, builder: MyFormBuilder) do |f| %>
<%= f.can_fill_in?(:title) do %>
<%= f.label :title %>
<%= f.text_field :title %>
<% end %>
<% end %>
您还可以将 rails 配置为默认使用您的自定义表单构建器:
ActionView::Base.default_form_builder = MyFormBuilder
看:
关于ruby-on-rails - 具有权威的 View 中的属性级别授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36686913/