iT邦幫忙

2022 iThome 鐵人賽

DAY 9
0
Software Development

SQL rookie 之天天魯一下系列 第 9

Day 9 - 插話:利用SampleDB seeding 資料(1)

  • 分享至 

  • xImage
  •  

哈囉,大家好!

到目前為止Model 關聯性終於建好了、資料庫也很粗淺地加上了關聯,但seeding tasks 遲遲還沒處理好,總覺得資料多樣性還是不夠。

前幾天多虧公司前輩指引了JSONPlaceholder 這網站,其主要用途為提供:

Free fake API for testing and prototyping.

但資料有關聯且多樣性非常夠,很適合用來當seeding data,爛書心想應該只要自己建立幾個Model 加上關聯,就能搭配這些data 使用了吧?呵......

可因為打API 返回的資料格式是JSON,這篇插話想介紹如何把這些資料跟自己的專案結合囉!

首先我們先來看JSONPlaceholder 的guide,可看到資料的關聯大致是:posts have many comments, albums have many photos......

而fetch Post API 返回的資料則是這形態:

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
...
]

而這些資料的來源網址為:https://jsonplaceholder.typicode.com/posts

因此我打算先建立一個Post Model 及其table,並嘗試用JSONPlaceholder 來seeding 我的Post data:

前置步驟:

# 1. new 專案、以PG 為database
❯ rails new rookie_sql_sample_db --database=postgresql

# 2. 建立資料庫
❯ rails db:create

# 3. create Model & table of Post
❯ rails g model Post userId:integer title:string body:string

# 4. 建立一個seedings task
❯ rails g task seeding_posts seed_posts

好了之後讓我們進去console 試試看吧!

require 'open-uri'
# 先require'open-uri' 的標準函式庫

open('https://jsonplaceholder.typicode.com/posts')
# 利用open 方法將JSON 來源網址存成一個IO 檔

open('https://jsonplaceholder.typicode.com/posts').read
# 讀取該IO 檔

❯ "[\n  {\n    \"userId\": 1,\n    \"id\": 1,\n    \"title\": \"sunt aut facere repellat provident occaecati excepturi optio reprehenderit\",\n    \"body\": \"quia et suscipit\\nsuscipit recusandae consequuntur expedita et cum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem eveniet architecto\"\n  },\n  {\n    \"userId\": 1,\n    \"id\": 2,\n    \"title\": \"qui est esse\",\n    \"body\": \"est rerum tempore vitae\\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\\nqui aperiam non debitis possimus qui neque nisi nulla\"\n  },\n  {\n    \"userId\": 1,\n    \"id\": 3,\n    \"title\": \"ea molestias q

# 應該就能看到資料啦!

接著我們修改剛剛的seeding task:

# 修改task
namespace :seeding_posts do
  desc "TODO"
  task seed_posts: :environment do
    puts "seeding posts"
    Post.destroy_all

    post_data = JSON.parse(open('https://jsonplaceholder.typicode.com/posts').read)
    post_data.each do |post|
      Post.create(userId: post["userId"], title: post["title"], body: post["body"])
    end
    puts "completed"
  end
end

執行task、進console
❯ rails seeding_posts:seed_posts

irb(main):001:0> Post.first
  Post Load (0.3ms)  SELECT "posts".* FROM "posts" ORDER BY "posts"."id" ASC LIMIT $1  [["LIMIT", 1]]
#<Post:0x00007fa36352e5c8> {
            :id => 1,
        :userId => 1,
         :title => "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
          :body => "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto",
    :created_at => Sat, 24 Sep 2022 10:05:04 UTC +00:00,
    :updated_at => Sat, 24 Sep 2022 10:05:04 UTC +00:00
}

就成功帶出資料囉!嘿嘿......

那麼今天的研究就到這邊,謝謝大家~~


上一篇
Day 8 - 為Model、Database 加上關聯(3)
下一篇
Day 10 - 插話:利用SampleDB seeding 資料(2)
系列文
SQL rookie 之天天魯一下30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言