---
title: "เพิ่ม type ใหม่ให้กับ attributes API ของ Rails 5"
description: "attributes API ของ Rails 5 ช่วยให้เราสร้าง form object ได้ง่ายมาก"
canonical: https://oozou.com/til/add-new-types-to-rails-5-attributes-api-13
locale: th
date: 2020-10-13
topic: ruby-on-rails
---

# เพิ่ม type ใหม่ให้กับ attributes API ของ Rails 5

> attributes API ของ Rails 5 ช่วยให้เราสร้าง form object ได้ง่ายมาก

Published: 2020-10-13 · Topic: [ruby on rails](https://oozou.com/th/til-topics/ruby-on-rails) ([markdown](https://oozou.com/th/til-topics/ruby-on-rails.md))

attributes API ของ Rails 5 ช่วยให้เราสร้าง form object ได้ง่ายมาก

ก่อนหน้านี้เราใช้ callback after\_initialize แปลงอีเมลเป็นตัวพิมพ์เล็ก แต่พอใช้โค้ดด้านล่าง เรากำหนด type :email เองได้ และค่าจะถูก cast ให้อัตโนมัติทุกครั้งที่เซ็ตค่า

ข้อดีคือการเรียกเซ็ตค่าอีเมลครั้งถัด ๆ ไปก็จะถูก cast ให้ด้วยเช่นกัน

```ruby
class EmailType < ActiveModel::Type::String
  def cast(value)
    return super unless value.is_a?(String)
    super(value.downcase)
  end
end

ActiveModel::Type.register(:email, EmailType)
```

```ruby
class Foo
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :email, :email
end
```

```ruby
> Foo.new(email: 'EMAIL@MAIL.com').email
=> 'email@mail.com'
```

---

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

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