Rails 如何创建模型之间的关系

Rails how to create relationships between models

我正在开发一个 Shopify 应用程序,我正在尝试在我的数据库中创建一个关系,其中我有一个 Shop 模型和一个 Address 模型,一个商店可以有不同的地址,每个地址都与一个商店相关.

所以我有这个:

models/shop.rb

class Shop < ActiveRecord::Base
  include ShopifyApp::SessionStorage
  has_many :addresses
end

models/address.rb

class Address < ApplicationRecord
    belongs_to :shop
end

db/migrate/create_shops.rb

class CreateShops < ActiveRecord::Migration[5.1]
    has_many :addresses
  def self.up
    create_table :shops  do |t|
      t.string :shopify_domain, null: false
      t.string :shopify_token, null: false
      t.timestamps
    end

    add_index :shops, :shopify_domain, unique: true
  end

  def self.down
    drop_table :shops
  end
end

db/migrate/create_shops.rb

class CreateAddresses < ActiveRecord::Migration[5.1]
  def change
    create_table :addresses do |t|
      t.text :Address1
      t.text :Address2
      t.string :Postal
      t.string :Phone
      t.string :City

      t.timestamps
    end
  end
end

我觉得我没有这个好... 那么,如何在我的数据库中添加商店地址?

谢谢。

我认为:

class CreateShops < ActiveRecord::Migration[5.1]
  has_many :addresses
  def self.up
    create_table :shops  do |t|
      t.string :shopify_domain, null: false
      t.string :shopify_token, null: false
      t.timestamps
    end

    add_index :shops, :shopify_domain, unique: true
  end

  def self.down
    drop_table :shops
  end
end

你不想has_many :addresses。还有这个:

class CreateAddresses < ActiveRecord::Migration[5.1]
  def change
    create_table :addresses do |t|
      t.text :Address1
      t.text :Address2
      t.string :Postal
      t.string :Phone
      t.string :City

      t.timestamps
    end
  end
end

应该是这样的:

class CreateAddresses < ActiveRecord::Migration[5.1]
  def change
    create_table    :addresses do |t|
      t.references  :shop
      t.string      :address_1
      t.string      :address_2
      t.string      :postal
      t.string      :phone
      t.string      :city

      t.timestamps
    end
  end
end

正如@engineersmnky 在评论中提到的那样,从 Rails 5 开始,会自动在外键上创建索引。

对于可能不在 Rails 5(或更晚,取决于你离未来多远)的未来读者,他们想要向外键添加索引...

如果您在 Rails 4.x,则执行:

class CreateAddresses < ActiveRecord::Migration
  def change
    create_table    :addresses do |t|
      t.references  :shop, index: true
      t.string      :address_1
      t.string      :address_2
      t.string      :postal
      t.string      :phone
      t.string      :city

      t.timestamps
    end
  end
end

如果您早于 Rails 4.x,请参阅 this question and answer