# Attribute Assignment

以 Hash 的形式给某个对象赋值，并且传递的属性经过 ForbiddenAttributesProtection 检查。

```
assign_attributes
```

是 update & update\_attributes 的底层实现。参数的类型都是 Hash 对象，但它不会触发 `save` 操作。

使用举例：

```ruby
# 直接赋值
cat = Cat.new(name: "Gorby", status: "yawning")
cat.attributes # => { "name" => "Gorby", "status" => "yawning", "created_at" => nil, 
                      "updated_at" => nil}

# 使用 Attribute Assignment
cat.assign_attributes(status: "sleeping")
cat.attributes # => { "name" => "Gorby", "status" => "sleeping", "created_at" => nil,
                      "updated_at" => nil }
```

原理上它和直接赋值是一样的（用了元编程一个个属性直接赋值），只是对于要传递的参数多了 ForbiddenAttributesProtection 检查。

对比直接赋值：

```ruby
user.is_admin = true
# 直接赋值，不涉及 ForbiddenAttributesProtection

user.assign_attributes is_admin: true
# ActiveModel::MassAssignmentSecurity::Error:
# Can't mass-assign protected attributes: is_admin
```

我们几乎不会直接使用 `assign_attributes` 给对象赋值。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kelby.gitbook.io/rails-beginner-s-guide/activemodel/active_model__rails/opts_attributeassignment.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
