LoginSignup
2
1

More than 5 years have passed since last update.

Railsで新しくテーブルをつくるときの手順メモ

Posted at

modelをつくる

$ bin/rails generate model Hoge

      invoke  active_record
      create    db/migrate/20180530064027_create_hoges.rb
      create    app/models/hoge.rb
      invoke    rspec
      create    spec/models/hoge_spec.rb
      invoke    factory_bot
      create    spec/factories/hoges.rb

modelをつくると、migrationとテスト(ここではspec)も自動で生成される。

modelにリレーションを貼る

class Hoge < ApplicationRecord
    belongs_to :fuga
    has_many :piyos // has_manyの場合は複数形(piyos)を使う

    validates :fuga_id
end

rails consoleで確認する

$ rails c


// Hogeモデルのオブジェクトを生成する
h = Hoge.new

id: nil,
fuga_id: nil


// Hogeモデルのオブジェクトからpiyoメソッドを呼び出す(今は空の状態)
h.piyos
=> []
2
1
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
1