I want to import the pull-down menu items when submitting a form in Rails into CSV and display them from the DB data.

Introduction

It is a memorandum for CSV importing pull-down menu items when submitting a form in Rails and displaying them using DB data.

environment

Reference URL

CSV import related https://qiita.com/Ryuta1346/items/c21cb70b9879c66c8639 https://qiita.com/SoarTec-lab/items/50e046ea2a2764c12c21 https://docs.ruby-lang.org/ja/latest/class/CSV.html https://qiita.com/3yatsu/items/416411c0a8f696dbf99e https://qiita.com/rllllho/items/672e336a03335cba6b34

Pull-down menu related https://qiita.com/HrsUed/items/56677d6c266d8a53ffa7 https://qiita.com/kawakami_shotaro/items/11a677bf34136cb7686d https://qiita.com/colorrabbit/items/b58888506e41d1370fd1 https://crieit.net/posts/Rails-collection-select https://qiita.com/_akira19/items/c218186983f444c2d794

Country code list CSV https://qiita.com/tao_s/items/3yy2b90a2751bfbdd585ea

Target

  1. CSV import pull-down menu choices
  2. Display the selection items in the pull-down menu using the DB data

It is an image of appearance ↓ form1.png

The pull-down menu choices are displayed using the column information saved in the DB ↓ form2.png

Implementation

I will explain CSV import and form pull-down separately.

1. CSV import pull-down menu choices

  1. Create Country model for saving country name list
  2. Add import process to db / seeds.rb
  3. Execute the import process with the rails command

The import process is performed using the CSV library of Ruby. This time, I imported the country name list from the following CSV. I added the created CSV file to the root directory.

country.csv


number,Country / region name,ISO 3166-English name in 1,number,Three characters,Two letters,place,Each administrative division
1,Iceland,Iceland,352,ISL,IS,Northern Europe,ISO 3166-2:IS
2,Ireland,Ireland,372,IRL,IE,Western Europe,ISO 3166-2:IE

For CSV, I used Country Code List CSV.

1. Country model creation

I created the following model. The region column is not used this time.

attribute type
country_name string
region string
#Country modeling
$ rails g model Country country_name:string region:string

2. Add import process

The import process has been added to seeds.rb. There seems to be a separate file and How to execute with runner command.

seeds.rb


require "csv"

#Specify the path to the CSV file as an absolute path
CSV.foreach("country.csv", headers: true) do |row|
  Country.create!(
    country_name: row["Country / region name"],
    region: row["place"]
  )
end

3. Execute the import process

Perform a CSV import with the rails command. I also wrote other processing in the seed file, so this time I deleted everything in the DB and imported it again.

#This is all you need to import a CSV and save it to your DB
$ rails db:seed

#Erase the DB and reinsert everything
$ rails db:migrate:reset
$ rails db:seed

#Check if it was imported in the rails console
$ rails c
#Check the number of imported country names
> Country.count
249

2. Display the selection items in the pull-down menu using the DB data

Modify the View file of the form submission at the time of new posting.

Ruby:view/model_names/new.html.erb


#Before correction
<%= form_with model: @model_name do |f| %>
  <%= f.label :country %>
  <%= f.text_field :country %>

  <%= f.submit "Send" %>
<% end %>

Ruby:view/model_names/new.html.erb


#Revised
<%= form_with model: @model_name do |f| %>
  <%= f.label :country %>
  <%= f.collection_select :country, Country.all, :id, :country_name, prompt: "Please select a country" %>

  <%= f.submit "Send" %>
<% end %>
# collection_select syntax
<%= f.collection_select <Column name of save destination>, <Array data for display>, <Column name of the value to save>,  <Column name for display>, <option> %>

Here The explanation about how to use collection_select is very easy to understand.

Learn

Recommended Posts

I want to import the pull-down menu items when submitting a form in Rails into CSV and display them from the DB data.
[Rails] I want to send data of different models in a form
[Rails] I want to display the link destination of link_to in a separate tab
I want to create a form to select the [Rails] category
I want to display an error message when registering in the database
[For beginners] I want to automatically enter pre-registered data in the input form with a selection command.
I want to morphologically analyze the log in the DB and put it in the DB to classify messages 1
I want to use a little icon in Rails
I want to define a function in Rails Console
I want to control the display of the upper management navigation bar (Control menu) in Liferay 7 / DXP
In Java, I want to trim multiple specified characters from only the beginning and end.
How to solve the problem when the value is not sent when the form is disabled in rails and sent
I want to call a method and count the number
[Rails] What to do when the error No database selected and Unknown database appears in db: migrate
[Controller] I want to retrieve the numerical value of a specific column from the DB (my memo)
I tried to sort the data in descending order, ascending order / Rails
I want to display the images under assets/images in the production environment
When log data accumulates in Rails and the environment stops working
[Rails] I want to add data to Params when transitioning with link_to
[Android] I want to get the listener from the button in ListView
I summarized the points to note when using resources and resources in combination
I want to select multiple items with a custom layout in Dialog
[Ruby] I want to display posted items in order of newest date
[Rails 6] cocoon_ Add id and data attributes to the form to be added
I want to display a PDF in Chinese (Korean) with thin reports
I want to get the IP address when connecting to Wi-Fi in Java
[Rails] [Parent-child relationship] I want to register the foreign key in the child with nil when the parent is deleted.
[Ruby] I want to make an array from a character string with the split method. And vice versa.
[Rails] I want to reset everything because the data in the local environment is strange! What to do before that
[For those who want to do their best in iOS from now on] Summary of the moment when I was surprised after developing an iOS application for two and a half years
What to do when rails db: seed does not reflect in the database
A memo to simply create a form using only HTML and CSS in Rails 6
Script to make yaml from CSV to put initial data in Rails with Fixtures
I want to get only the time from Time type data ...! [Strftime] * Additional notes
How to make a unique combination of data in the rails intermediate table
I want to recursively get the superclass and interface of a certain class
I tried to express the phone number (landline / mobile phone) with a regular expression in Rails and write validation and test
Even if I want to convert the contents of a data object to JSON in Java, there is a circular reference ...
[Ruby] When you want to assign the result obtained by conditional branching to a variable and put it in the argument
I want to find the MD5 checksum of a file in Java and get the result as a string in hexadecimal notation.