0

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

所以我有这个:

模型/shop.rb

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

模型/地址.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

我想我没有这个好... 那么,我怎样才能将地址​​添加到我的数据库中的商店?

谢谢你。

4

1 回答 1

0

我认为这里:

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,请查看此问题和答案

于 2017-11-30T19:40:20.110 回答