I want Rails to save two-dimensional arrays to the database.

Asked 2 years ago, Updated 2 years ago, 32 views

on Ruby on Rails
[
  ["Korean", "1", "B", "2019"],
  ["Math", "2", "A", "2019"],
  ["Science", "2", "B", "2017"]
  ["Society", "2", "C", "2019"],
  ["Art", "2", "A", "2016"]
  ["Information", "2", "S", "2017"]
]

I would like to take the elements one by one from these two-dimensional arrays and save them in the database in Curriculum.new, but I can't get the image of the code, so could someone please tell me?
The structure of the database is as follows.

Enter a description of the image here

ruby-on-rails ruby

2022-09-29 21:51

1 Answers

I didn't do it, so there might be some mistakes, but

Can't I write rakedb:seed on db/seeds.rb like this?

bulk_arrays=[
  ["Korean", "1", "B", "2019"],
  ["Math", "2", "A", "2019"],
  ["Science", "2", "B", "2017"]
  ["Society", "2", "C", "2019"],
  ["Art", "2", "A", "2016"]
  ["Information", "2", "S", "2017"]
]

bulk_values=bulk_arrays.map {|r|
  # Change column name as appropriate
  Curriculum.new {
    Class Name: r[0],
    Units: r[1],
    Year: r[3]
  }
}

Curriculum.import bulk_values

The model has already been defined, so I think there is already a table
If you don't have it, you'll need to migrate the tables.

railsg migration create_curriculums

to the migration file db/migrate/xxxx_create_curriculums made of
 create_table: curriculums do | t |
  t.string 'Lesson Name' # Added
  t.string 'Number of Units' # Added
  t.sting 'Year' # Added
end


by writing
rails db:migrate
I think we can have a table.


2022-09-29 21:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.