[Ruby] Use collection_select to pull down the data stored in Active_Hash

1 minute read

Overview

What I would like to implement this time is to store the information that does not change such as the shipping source and the state of the product as Active_Hash when implementing the product listing function, and display it as a pull-down in the view file.

For how to store the prefectures etc. in Active_Hash, I wrote another article, so please refer to that.

About Active Hash

What is ##collection_select It is one of the helper methods, and it is the description that can display the value given the key in the select box.

The basic description is

ruby:xxx.html.erb


f.collection_select(: column name, array of elements, item of value attribute, item of text, {prompt: "Please select"}

It seems that

Example

This time, I will leave an example of implementing the presence or absence of shipping fee as PostageType class when listing products.

ruby:products/new.html.erb


<%= f.collection_select(:postage_type, PostageType.all, :id, :name, {}, {class:"select-box", id:"item-shipping-fee-status"}) %>

If the prompt part is empty, Active Hash’s :id=1 seems to be displayed as the default pull-down.

Also write down the description of postage_type Active Hash.

models/postage_type.rb


class PostageType <ActiveHash::Base
  self.data = [
    {id: 1, name:'---'}, {id: 2, name:'Cash on delivery (paid by buyer)'}, {id: 3, name:'Shipping included (paid by seller)'}
  ]
end

As an aside, let’s describe the class name in the upper camel case. I got an error and got lost once…

Tags: ,

Updated: