2
0

More than 3 years have passed since last update.

Railsでワクワク個人開発  第3回:データの関連付け/ seedデータ投入

Posted at

関連付けとモデル

 日々の記憶がおぼろげだが、ここに記しておこう。関連づけられたデータを作成してみることにした。DB設計の段階から、ユーザーと彼らがもつ植物は関連付けようと考えていた。一人のUserは複数のPlantを所持する。共有することはしない。

 Userモデルはさきの記事でmigrateした。今回はPlantモデルをつくる。
rails g model plant をターミナルに打ち込むとplantができる。便利だ。 db/migrateフォルダから対応するファイルを開く。こんな感じで書く。

class CreatePlants < ActiveRecord::Migration[6.0]
  def change
    create_table :plants do |t|
      t.integer :user_id, null: false
      t.string :plant_name, null: false
      t.string :img
      t.timestamps
    end
  end
end

 このときにDB設計が生きてくる。場当たり的にこれらを設定するのはうまくいかない。
終了したらmigrateをしよう。

モデルクラスの修正

 関連付けのお約束。モデルクラスの修正をした。

app/model/plant.rb

class Plant < ApplicationRecord
  belongs_to :user
end

app/model/user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  has_many :plants
end

plantはuserに属している、userは多くのplantを持っている。ということを書いた。

seedデータ投入

 ここで、タネを入れる。seedとかいうサンプルデータをあらかじめ入れておく。

db/seed.rb

User.create(email: 'test@example.com', password: 'password')
User.create(email: 'test2@example.com', password: 'password')
Plant.create(user_id:1, plant_name: "flower", img: "flower_img") 
Plant.create(user_id:1, plant_name: "sun_flower", img: "sun_flower_img") 
Plant.create(user_id:2, plant_name: "dia", img: "dia_img") 
Plant.create(user_id:3, plant_name: "rose", img: "rose_img") 

ターミナルで rails db:seed と打つ。これでOK。 終了したらrailsのコンソールからデータを確認しよう。 rails cでできる。

 User.allと打ち込んだらいいぐあいに表示されるだろうか。よし。

次回予告

 いよいよネストされたリソースを使ってCRUD処理を書く。このあたり、途中経過がよくわからなくなっているので、結果だけ書いていく。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0