[RUBY] [Rails] Various ways to write in seed files

environment

Ruby 2.6.5 Rails 6.0.3

How to write this and that

① Create only one (basic)

seed.rb


User.create!(
   email: "[email protected]",
   name: "user1",
   passowrd: "password"
)

Create! Action for the model you want to create a record for. I will give the value of each column.

② Create multiple demo data

seed.rb


 users = User.create!([
  {nickname: "guest", email: "[email protected]", password: "guest1234"},
  {nickname: "guest2", email: "[email protected]", password: "guest5678"}, 
])

Prepare an array. It can be created by passing record data in the form of a hash to each element of the array.

③ Create multiple demo data (repetitive processing)

seed.rb


20.times do |n|
  User.create!(
  name: "guest#{n+1}",
  email: "guest#{n+1}@guest.com",
  password: "guest#{n+1}0000",
 )
end

Execute the create! Action multiple times using the times method. Implement different values in each record by including n in the value so that columns with uniqueness do not overlap.

④ Combine arrays

seed.rb


stations = ["Tokyo",
  "Yurakucho",
  "Shimbashi",
  "Hamamatsucho",
  "Tamachi",
  "Takanawa Gateway",
  "Shinagawa",
  "Osaki" ,
  "Gotanda",
  "Meguro",
  "Ebisu",
  "Shibuya",
  "Harajuku",
  "Yoyogi",
  "Shinjuku",
  "Shin-Okubo",
  "Takadanobaba",
  "Mejiro",
  "Ikebukuro",
  "Otsuka",
  "Sugamo",
  "Komagome",
  "Tabata",
  "Nishinippori",
  "Nippori",
  "Uguisudani" ,
  "Ueno",
  "Okachimachi",
  "Akihabara",
  "Kanda"]

stations.length.times do |i|
  Station.create!(
    name: stations[i]
  )
end

After preparing the array, iterate as many times as there are, and give the value of the array to the column. (I think I should be able to go with each, but for some reason it didn't work and I processed it with times) I used an array because I wanted to reuse this value for another column. (Specifically, when I made the demo data of the restaurant after this, I wanted to include the station name in the store name, so I chose this method)

⑤ Create a record including attributes nest

seed.rb


Item.create!(
  name: "sofa",
  produce: "Brand new",
  price: 8000,
  images_attributes: [{image: File.open('./app/assets/images/index_item01.png',)}]
  )

When the Item table nests the Image table and has a has_many relationship. Since images_attributes has multiple record data, create an array and give the record data of the Image table by hash in it.

⑥ Various combinations so far

seed.rb


10.times do |i|
  Shop.create!(
    name: "Fresh fish shop#{stations[i]}shop",
    address: addresses[i],
    capacity: 40,
    mainimage: File.open('./app/assets/images/shops/shop1_1.jpg'),
    maincontent: "We are waiting for you to prepare seafood directly from the production area!",
    likepoints: 0,
    station_ids: [i+1,i+2],
    introduces_attributes: [
      {subcontent: "You can enjoy your meal in the calm interior.",
        number: 1,
        subimage: File.open('./app/assets/images/shops/shop1_2.jpg')},
      {subcontent:"We recommend the seafood platter!",
        number: 2,
        subimage: File.open('./app/assets/images/shops/shop1_3.jpg')},
      {subcontent: "A talkative clerk is waiting for you!",
        number: 3,
        subimage: File.open('./app/assets/images/shops/shop1_4.jpg')}
    ]
  )
end

Multiple shop data are created using the array called stations. The shop table nests the introduces table, and I want to pass multiple records to the introduces table, so I pass an array in the form of a hash. It's not that complicated, surprisingly. (I don't know the cause, but this didn't work at first, and when I adjusted the indentation, something went wrong.

Summary

When I studied how the data was sent in the form, I understood a lot, so I didn't have to worry too much about the description in the seed file. While reading various things, I got the impression that the phrase "the array is taken out as a hash and the hash is taken out as an array to save the data" that came out in the official text was very easy to understand (remember).

I will leave it as a reminder.

Recommended Posts

[Rails] Various ways to write in seed files
How to write Rails seed
[Rails] Two ways to write form_with
[Rails] How to write in Japanese
[Rails] Various ways to delete data
How to write Rails
How to write a date comparison search in Rails
[Rails 6] Add images to seed files (using Active Storage)
How to write Rails validation
[Rails] How to make seed
How to write Rails routing
[Rails5] japanMap link How to write parameters in js.erb file
[Rails] How to write user_id (foreign key) in strong parameter
Rails on Tiles (how to write)
[Rails] How to write exception handling?
How to introduce jQuery in Rails 6
How to install Swiper in Rails
How to write the view when Vue is introduced in Rails?
# 8 seed implementation to build bulletin board API with authentication authorization in Rails 6
How to implement search functionality in Rails
How to change app name in rails
How to insert a video in Rails
Java-How to compare image files in binary
[Java] How to output and write files!
How to use MySQL in Rails tutorial
Convert SVG files to PNG files in Java
Steps to set a favicon in Rails
[rails] How to configure routing in resources
To write Response data directly in Spring
I will write 5 ways to implement Java Singleton and various advantages and disadvantages
How to implement ranking functionality in Rails
How to use credentials.yml.enc introduced in Rails 5.2
[Rails / JavaScript / Ajax] I tried to create a like function in two ways.
What to do when rails db: seed does not reflect in the database
Rails: How to write a rake task nicely
Convert to a tag to URL string in Rails
Two ways to start a thread in Java + @
[JavaFX] How to write Eclipse permissions in build.gradle
[Rails] How to write when making a subquery
I tried to organize the session in Rails
3 ways to import the library in Android Studio
[Rails] How to use select boxes in Ransack
JUnit 5: How to write test cases in enum
How to translate Rails into Japanese in general
How to prevent direct URL typing in Rails
How to update pre-built files in docker container
How to separate .scss by controller in Rails
How to conditionally add html.erb class in Rails
One way to redirect_to with parameters in rails
How to implement a like feature in Rails
How to easily create a pull-down in Rails
How to use JQuery in js.erb of Rails6
[Rails] Added in devise: username not added to database
[Ruby on Rails] How to install Bootstrap in Rails
How to make a follow function in Rails
How to write Java String # getBytes in Kotlin?
Rails "How to delete NO FILE migration files"
[Rails] How to use PostgreSQL in Vagrant environment
How to check Rails commands in the terminal
ActiveModel :: MissingAttributeError (can't write unknown attribute 〇〇) in Rails
Notes on how to write comments in English