プロダクト開発日誌

技術のことなど

【Rails】1対多のリレーションを作成

Zoneモデルを作成し、AreaモデルとZoneモデルを1対多のリレーションを作成します。

Zoneモデルの作成

bin/rails g scaffold Zone name:string description:text

Migration File

class CreateZones < ActiveRecord::Migration[6.0]
  def change
    create_table :zones do |t|
      t.string :name, null: false, unique: true
      t.text :description

      t.timestamps
    end
  end
end

Migration

bin/rails db:migrate
bundle exec annotate

1対多のRelation

bin/rails g migration add_area_ref_to_zones area:references
class AddAreaRefToZones < ActiveRecord::Migration[6.0]
  def change
    add_reference :zones, :area, foreign_key: true
  end
end
bin/rails db:migrate
bundle exec annotate

models/zone.rb

belongs_to :area

models/area.rb

has_many :zones