ActiveHash By directly describing the unchanged data such as occupation selection in the model file, the data can be handled without saving it in the database. In other words, by using Active_Hash, ActiveRecord methods can be used for the unchanged data described directly in the model file.
Gemfile
qiita.rb
gem 'active_hash'
After writing, execute bundle install.
In conclusion, use --skip-migration. The reason is not to create a database. That is, the migration file is no longer needed. Note that if you use the rails g model command here, a migration file will be created at the same time.
%rails g model model name--skip-migration
ActiveHash::Base You can use the same methods as ActiveRecord. In other words, by inheriting ActiveHash :: Base, ActiveRecord methods can be used for the objects defined in the model.
qiita.rb
class ShippingFee < ActiveHash::Base
self.data = [
{ id: 0, name: '---' },
{ id: 1, name: 'Cash on delivery(Buyer burden)' }, { id: 2, name: 'postage included(Exhibitor burden)' }
]
end
Image of creating a table with self.data. The data is stored in an array in hash format.
belongs_to_active_hash Normally, it will be belongs_to: model name, but if you want to set an association for a model created using ActiveHash, use belongs_to_active_hash method.
collection_select Method that can display data in pull-down format
Description order | Details | Concrete example |
---|---|---|
First argument | Method name | Column name |
Second argument | object | Specification of array data |
Third argument | id | Reference DB column name |
Fourth argument | name | Actual column name |
Fifth argument | prompt | What you want to display at the top of the pull-down |
option | name of the class | -- |
qiita.rb
<%= f.collection_select(:shipping_fee_id, Shipping_fee.all, :id, :name, {}, {class:"select-box", id:"item-shipping-fee-status"}) %>
I've listed some typical ones ·Prefectures ・ Occupation selection ・ Closed question (like answering yes or no) ·questionnaire ・ Category ・ Product status
Personally, I felt that this would greatly reduce the stress on the user side and that it would be possible to collect information efficiently. It may be good to use it when you want to ask the other party for their opinions.
Thank you for reading the article so far.
ActiveHash is also incorporated into things that you use casually. It's easy to implement, so I wanted to use it positively.
I would like to continue to provide useful information as I continue to study, so I look forward to working with you.
Thank you very much for reading the article so far!
Recommended Posts