MENU

ActiveModel::Attributesを使ってみる

## ActiveModel::Attributesとは何か?

 

モデルカラムにアクセスする動作ができるようになるみたい

 

## 使い方

 

とりあえず試してみる

 

```ruby

class Order

  include ActiveModel::Model

  include ActiveModel::Attributes

  attribute :title

  attribute :price

end

```

- newをして見るとこんな感じ

```ruby

[17] pry(main)> order = Order.new
=> #<Order:0x007fb3270eafd8
@attributes=
#<ActiveModel::AttributeSet:0x007fb3270eaf88
@attributes=
{"title"=>
#<ActiveModel::Attribute::WithCastValue:0x007fb3270eaf10
@name="title",
@original_attribute=nil,
@type=#<ActiveModel::Type::Value:0x007fb32908c030 @limit=nil, @precision=nil, @scale=nil>,
@value_before_type_cast=nil>,
"price"=>
#<ActiveModel::Attribute::WithCastValue:0x007fb3270eaee8
@name="price",
@original_attribute=nil,
@type=#<ActiveModel::Type::Value:0x007fb3288faa10 @limit=nil, @precision=nil, @scale=nil>,
@value_before_type_cast=nil>}>>

```

 

- 編集などは直接アクセスできるみたい

 

```

[18] pry(main)> order.attributes
=> {"title"=>nil, "price"=>nil}
[19] pry(main)> order.title
=> nil
[20] pry(main)> order.title = "hello"
=> "hello"
[21] pry(main)> order.title
=> "hello"

```

 

## まとめ

 

attr_accessorなどでこれらの内容を再現できるけど、

これはこれで簡単そうで良い