# Understanding the Attribute Assignment API in Rails

*Published on March 23, 2023*

Tags: Rails Internals

---


Here's a regular Ruby class with two properties and a constructor. To create a new instance of the class, you have to pass the arguments expected by the constructor,&nbsp;**in the same order**.

```ruby
class Person
  attr_accessor :name, :age
  
  def initialize(name, age)
    @name = name
    @age = age
  end
end

# create a new object
akshay = Person.new('Akshay', 31)
```

However, if you've worked with ActiveRecord models in Rails, you must have noticed that they don't include the&nbsp;`initialize`&nbsp;method. Still, you can create them using the&nbsp;`new`&nbsp;method, passing in a hash of attributes in any order.

```ruby
class Post < ApplicationRecord
end

# create a new post
post = Post.new(title: 'hello world', body: 'how are you?')
```

If you try this with a plain Ruby class, it throws an error.

```ruby
akshay = Person.new(name: 'Akshay', age: 31)

# wrong number of arguments (given 1, expected 2) (ArgumentError)
```

So the question is:&nbsp;**How does Rails make it work? 🤔**

## The AttributeAssignment Module

The answer lies in the&nbsp;`ActiveModel::AttributeAssignment`&nbsp;module, which includes the&nbsp;`assign_atributes`&nbsp;method. It allows you to set all the attributes by passing in a hash of attributes. The hash keys must match the attribute names.

```ruby
class Language
  include ActiveModel::AttributeAssignment
  attr_accessor :title, :author
end

ruby = Language.new
ruby.assign_attributes(title: "Ruby", author: "Matz")

ruby.title # => 'Ruby'
ruby.author # => 'Matz'

ruby.assign_attributes(author: "Yukihiro Matsumoto")

ruby.title # => 'Ruby'
ruby.author # => 'Yukihiro Matsumoto'
```

Under the hood, the&nbsp;`assign_attributes`&nbsp;method calls the&nbsp;`assign_attribute`&nbsp;method for each key-value pair.

Here's the internal implementation of this method.

```ruby
def _assign_attribute(k, v)
  setter = :"#{k}="
  if respond_to?(setter)
    public_send(setter, v)
  else
    raise UnknownAttributeError.new(self, k.to_s)
  end
end
```

Let's try to understand what's going on when we pass&nbsp;`name: 'Akshay'`&nbsp;when initializing the object.

1. The&nbsp;`setter`&nbsp;will be set to&nbsp;`:name=`
2. The&nbsp;[`respond_to?`](https://ruby-doc.org/3.2.1/Object.html#method-i-respond_to-3F)&nbsp;method checks if our class includes the&nbsp;`name=`&nbsp;method, which sets the name. If it does, it calls that method.
3. Since our class uses the&nbsp;`attr_accessor :name`&nbsp;directive, the&nbsp;`name=`&nbsp;method is present. &nbsp;Hence it calls the setter method, setting the value 'Akshay' for the&nbsp;`name`&nbsp;attribute.
4. For attributes not defined via&nbsp;`attr_accessor`&nbsp;,&nbsp;`attr_writer`&nbsp;or via overridden methods, it raises the&nbsp;`UnknownAttributeError`.

**That's nice, but how can you create new objects?**

On its own, the&nbsp;`AttributeAssignment`&nbsp;module won't allow you to call the&nbsp;`new`&nbsp;method to create new objects. For that, you need the&nbsp;`ActiveModel::API`&nbsp;module.

The&nbsp;`API`&nbsp;module includes the&nbsp;`AttributeAssignment`&nbsp;module and provides an&nbsp;`initialize`&nbsp;method. This method takes an&nbsp;`attributes`&nbsp;hash as argument and calls the&nbsp;`assign_attributes`&nbsp;method, passing the hash.

```ruby
module ActiveModel
  module API
    include ActiveModel::AttributeAssignment
    
    def initialize(attributes = {})
      assign_attributes(attributes) if attributes
      super()
    end
  end
end
```

If you include the&nbsp;`ActiveModel::API`&nbsp;module in your plain Ruby classes and remove the constructor, you can create new instances like Active Record models.

```ruby
class Person
  include ActiveModel::API
  
  attr_accessor :name, :age
end

# akshay = Person.new(name: 'Akshay', age: 31)
=> #<Person:0x000000010d045b60 @age=31, @name="Akshay">
```

## How Do Rails Models Get This Behavior?

All Active Record models inherit from the&nbsp;`ApplicationRecord`&nbsp;class, which inherits from the&nbsp;`ActiveRecord::Base`&nbsp;class. The&nbsp;`Base`&nbsp;class includes the `ActiveRecord::AttributeAssignment` module. Finally, this module includes the `ActiveModel::AttributeAssignment`&nbsp;module.

![attributes.webp](https://writesoftwarewell.com/media/sjls7spcdfo2l6usdm3u8nddkyrx.webp "Attribute Assignment")

Now, the&nbsp;`ActiveRecord::AttributeAssignment`&nbsp;module provides&nbsp;[its own internal implementation](https://github.com/rails/rails/blob/main/activerecord/lib/active_record/attribute_assignment.rb)&nbsp;for the private methods, but that's a topic for another blog post.

I hope this post helped you gain a deeper understanding of the&nbsp;`AttributeAssignment`&nbsp;module. You can use it with plain Ruby classes to simplify your code. You can even use this feature outside Rails by only using the ActiveModel framework and including the&nbsp;`ActiveModel::API`&nbsp;module.

