I am making an original app with Rails. I applied Active Hash to this app. Enabled to select the data set in ActiveHash in pull-down format. I will write it down so that I can remember it even if I forget it.
Development environment ruby 2.6.5 Rails 6.0.3.4
Active Hash is one of the Gem. Add to the Gem file and install in the terminal.
Gemfile
gem 'active_hash'
Terminal
bundle install
Here, day is the target of Active Hash. When creating a model-If skip-migration is added, the migration file will not be created. If there are other ActiveHash targets, create as many models as there are.
Terminal
rails g model day --skip-migration
Inherit ActiveHash in the model. self.data is an array that stores hash format data. In the hash, id and name (days) are linked.
app/models/day.rb
class day < ActiveHash::Base #← Inherit ActiveHash
self.data = [
{ id: 1, name: '--' },
{ id: 2, name: '1 day' },
{ id: 3, name: '1 week' },
]
end
Next, set to save the id of the number of days set above in the database. Take article as an example of the table to which ActiveHash is linked.
2020***********_create_articles.rb
class CreateArticles < ActiveRecord::Migration[6.0]
def change
create_table :articles do |t|
t.string :title , null: false
t.text :text , null: false
t.integer :day_id , null: false #Column where ActiveHash id is stored
t.timestamps
end
end
end
Don't forget to migrate. Model associations too.
app/model/article
validates :day_id # _Add id
belongs_to_active_hash :day # _no id required
Add day_id to the strong parameter so that it can be saved.
ruby:article.controller.rb
Example:
def new
@article = Article.new
end
def create
@article = Article.new(article_params)
end
private
def article_params
params.require(:article).permit(:title, :text, :day_id)
end
It can be displayed in pull-down format by collection_select. The arguments are from 1st to 5th.
argument | value |
---|---|
First argument(Column to be saved) | day_id |
Second argument(Array of objects) | Day.all |
Third argument(Items stored in columns) | id |
Fourth argument(Column name displayed in the options) | name |
Fifth argument(option) | {} |
html option | {class:"day-select"} |
<%= f.collection_select(:day_id, Day.all, :id, :name, {}, {class:"day-select"}) %>
that's all
Recommended Posts