0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【rails】activehashについて

Posted at

###Active Hashとは
ハッシュ形式の値をActive Recordと同じように操作できるようにするgem
Relationも貼れるので便利

###基本的な使い方
以下のような書き方ができる

app/models/plan.rb
class Plan < ActiveHash::Base
  self.data = [
    {id: 1, name: "free"},
    {id: 2, name: "silver"},
    {id: 3, name: "gold"},
  ]
end

class Plan < ActiveHash::Base
  self.data = [
    {id => 1, name => "free"},
    {id => 2, name => "silver"},
    {id => 3, name => "gold"},
  ]
end

class Plan < ActiveHash::Base
  fields :name
  add id: 1, name: "free"
  add id: 2, name: "silver"
  add id: 3, name: "gold"
end
ターミナル
pry(main)>Plan.first
=> #<Plan:0x00007ffd3d2c43f8 @attributes={:id=>1, :name=>"free"}>

relationを貼りたいモデルに以下を記載すればアソシエーションを利用してデータを操作できる。 ActiveHashのモデル側には特に追記することはない
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to_active_hash :ActiveHashのモデル名

参考
https://qiita.com/DON4024/items/78edb7a309ee96766952
https://qiita.com/Toman1223/items/8633142312bfa886d50b

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?