---
title: "用 Pundit Policy 管理 permitted parameters、默认值与各 action 的参数"
description: "要管理 permitted params，你可以在你的 policy 中加入 permitted\\attributes 和 permitted\\attributes\\for\\#{action}，例如"
canonical: https://oozou.com/til/use-pundit-policies-to-manage-permitted-parameters-defaults-and-per-action-188
locale: zh-Hans
date: 2022-02-10
topic: ruby-on-rails
---

# 用 Pundit Policy 管理 permitted parameters、默认值与各 action 的参数

> 要管理 permitted params，你可以在你的 policy 中加入 permitted\attributes 和 permitted\attributes\for\#{action}，例如

Published: 2022-02-10 · Topic: [ruby on rails](https://oozou.com/zh-Hans/til-topics/ruby-on-rails) ([markdown](https://oozou.com/zh-Hans/til-topics/ruby-on-rails.md))

要管理 permitted params，你可以在你的 policy 中加入 permitted\_attributes 和 permitted\_attributes\_for\_#\{action}，例如

```ruby
class CommentPolicy < ApplicationPolicy
  def permitted_attributes
    %i[body]
  end

  def permitted_attributes_for_create
    %i[body application_id]
  end
end
```

然后在你的 controller 里

```ruby
class CommentController
  def create
    @comment = Comment.create(comment_attributes) # { body: 'body', application_id: 1 }
  end
 
  def update
    @comment = Comment.find(params[:id])
    @comment.update(comment_attributes) # { body: 'new body' }
  end
 
  private def comment_attributes
    permitted_attributes(Comment)
  end
end
```

---

Contact OOZOU: hello@oozou.com · +66 2544 0000 · https://oozou.com/zh-Hans/contact

More for AI agents: https://oozou.com/llms.txt · every page has a markdown twin at its URL plus ".md"
