2017-11-30 4 views
0

Shopify 앱을 개발 중이며 Shop 모델과 주소 모델이있는 데이터베이스에서 관계를 만들고 싶습니다. 한 상점은 다른 주소와 모든 주소를 가질 수 있습니다 한 상점과 관련이 있습니다./shop.rb레일 사이의 관계를 만드는 방법

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

모델/address.rb

class Address < ApplicationRecord 
    belongs_to :shop 
end 

dB/마이그레이션/create_shops.rb

모델 :

그래서 나는이 있습니다

나는이 잘 ... 그래서, 어떻게 내 데이터베이스의 가게에 주소를 추가 할 수없는 생각/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 

dB/마이그레이션?

고맙습니다.

답변

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 

, 레일 5로, 인덱스가 자동으로 외래 키에 생성됩니다. 레일에 5하지 않을 수 있습니다 미래의 독자

(또는 그 이후에 따라 얼마나 멀리 당신이 미래에) 당신이 경우 외래 키에 인덱스를 추가 할 ...

4.x의 레일, 다음을 수행하십시오 이전 레일 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

하! 좋은 캐치. 나는 다른 분야의 필드 유형에주의를 기울이지도 않았다. 감사! – jvillian

+0

또한'references'는 인덱스를 기본으로 추가하므로 두 번째 예제는 중복됩니다 – engineersmnky

관련 문제