2017-11-30 6 views
0

私はShopifyアプリケーションを開発しています。ショップモデルと住所モデルを持つデータベースで関係を作成しようとしています。 1つのショップに関連しています。/shop.rbモデル間の関係を作成する方法を教えてくださいレール

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

モデル/ address.rb

class Address < ApplicationRecord 
    belongs_to :shop 
end 

デシベル/移行/ 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 

デシベル/移行/ 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 

... だから、どのように私は、データベース内の店にアドレスを追加することができますか?

ありがとうございます。

答えて

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 

は次のようにする必要があります:コメントで@engineersmnkyで述べたように

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 

、Railsの5のように、インデックスが自動的に外部キーに作成されます。 Railsの上5ではないかもしれない将来の読者のために

(以降、に応じて、どこまであなたが未来への)あなたがしている場合は、外部キーにインデックスを追加したい...

4.xのレール、その後、実行します。以前のRailsの4.x以上であれば、その後、this question and answerを参照してください

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 

+1

あなたが4000文字以上の住所を知っていない限り、おそらく 'string'でもアドレス行に十分です。 – engineersmnky

+0

Ha!良いキャッチ。私は他のフィールドのフィールドタイプにも注意を払っていませんでした(私の悪い)。ありがとう! – jvillian

+0

また、 'references'はデフォルトでインデックスを追加するので、2番目の例は冗長です。 – engineersmnky

関連する問題