[Ruby] [Rails] About active hash

less than 1 minute read

What is Active Hash

A gem that allows you to manipulate hashed values like Active Record It is convenient because you can also attach a Relation

Basic usage

Can be written as

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

terminal


pry(main)>Plan.first
=> #<Plan:0x00007ffd3d2c43f8 @attributes={:id=>1, :name=>"free"}>


If you write the following in the model you want to attach the relation, you can manipulate the data using the association. There is no particular addition to the model side of ActiveHash

extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to_active_hash: ActiveHash model name

###

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

Tags: ,

Updated: