[Rails] About active hash

What is Active Hash?

A gem that allows you to manipulate hashed values in the same way as Active Record Convenient because you can also paste Relation

Basic usage

You can write as follows

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 describe the following in the model to which you want to paste the relation, you can manipulate the data using the association. There is nothing to add to the model side of ActiveHash
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to_active_hash :Active Hash model name

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

Recommended Posts

[Rails] About active hash
[Rails] Introducing Active Hash
About Rails 6
gem active_hash About active hash
[About double hash]
About Rails controller
[Ruby on Rails] About Active Record callbacks
About rails version specification
Pitfalls of Active Hash
[rails] About devise defaults
About rails strong parameters
Table design (using Active Hash)
About naming Rails model methods
[Rails] About scss folder structure
[Rails] About Rspec response test
About Rails scraping method Mechanize
What is Rails Active Record?
Hash
[Rails] About implementation of like function
[Rails] About helper method form_with [Basic]
[Rails] How to use Active Storage
About =
I tried to explain Active Hash
[Rails 6.0] About batch saving of multiple records
Rails Active Storage shrinks images before uploading
[Rails] About local: true described in form_with