2010-12-11 2 views
2
나는 다음과 같은 모델이

:기본 레일 질문 - 데이터베이스에 새 항목을 만드는 방법?

Product: name, shop_id (foreign key), brand_id (foreign key), price 
Shop: name 
Brand: name 

연관성은 다음과 같습니다

Product: belongs_to :shop 
     belongs_to :brand 
Shop: has_many :products 
     has_many :brands, :through => :products 
Brand: has_many :products 
     has_many :shops, :through => :products 

질문 1

이 단체는 의미가됩니다? 다른 협회를 추가 하시겠습니까?

질문이 내가 db/seeds.db에서 미리 채울 데이터베이스 싶습니다.

Shop.create(:name => shop_name) 
Brand.create(:name => brand_name) 

는 무엇 Product를 추가 할 수있는 가장 적절한 방법이 될 것입니다 :

는이 Shop 또는 Brand 내가 추가하려면? shop_idbrand_id 값을 수동으로 삽입해야합니까? 새로 생성 된 제품의 상점과 브랜드가 아직 존재하지 않으면 데이터베이스에 자동으로 추가됩니까?

답변

5

일반적인 아이디어를 해결할 수있는 것은이 작업을 수행하는 것입니다. 원치 않는 경우 조인 모델을 수동으로 생성 할 필요가 없습니다.

편집 : 아래에 의견에 대한 데모가 있습니다.

마이그레이션을 설정하십시오.

$ ./script/rails g model Shop name:string 
$ ./script/rails g model Brand name:string 
$ ./script/rails g model Product brand_id:integer shop_id:integer 
$ rm test/fixtures/* 

$ rake db:migrate; rake db:test:prepare 

모델입니다.

class Brand < ActiveRecord::Base 
    has_many :products 
    has_many :shops, :through => :products 
end 

class Shop < ActiveRecord::Base 
    has_many :products 
    has_many :brands, :through => :products 
end 

class Product < ActiveRecord::Base 
    belongs_to :brand 
    belongs_to :shop 
end 

테스트입니다. 코드 행은 명시 적으로 제품을 작성하지 않습니다.

require 'test_helper' 

class ShopTest < ActiveSupport::TestCase 

    def test_brand_assignment_to_shop 
    assert_equal 0, Product.count 

    shop = Shop.create(:name => "Foo Shop") 
    brand = Brand.create(:name => "Foo Brand") 
    shop.brands << brand 

    assert_equal 1, Product.count 
    assert_equal shop.id, Product.first.shop_id 
    assert_equal brand.id, Product.first.brand_id 
    end 
end 



$ ruby -I./test test/unit/shop_test.rb 
Loaded suite test/unit/shop_test 
Started 
. 
Finished in 0.029778 seconds. 

1 tests, 4 assertions, 0 failures, 0 errors 
+0

감사합니다.하지만 주된 질문은 '제품'삽입에 관한 것입니다 ... –

+1

시도해 보셨습니까? 제품 삽입은 코드가 수행 할 작업과 정확히 일치합니다. – jdl

+0

노력에 감사드립니다! 나는 왜'shop.brands << brand'가 제품을 추가하는지 이해하지 못한다. 당신은 정교 할 수 있습니까? 이 제품의 '이름'과 '가격'을 어떻게 정의 하시겠습니까? –

1

제품 모델을 만들 때 해당 연결이 올바른지 확인하십시오.

accepts_nested_attributes_for을 사용하면 부모를 통해 연결된 레코드의 특성을 저장할 수 있습니다.

시드의 경우 수동으로 shop_id 및 brand_id를 삽입해야합니다.

@shop = Shop.create(:name => shop_name) 
@brand = Brand.create(:name => brand_name) 

Product.create(:shop_id => @shop.id , :brand_id => @brand.id) 

먼저 부모가 자녀 그럼 작성해야 명심 데이터를 삽입하는 동안 제품을

희망이 먼저 가게와 브랜드를 만든 다음 생성, 다음과 같이이 수행 할 수 있습니다

shop = Shop.create(:name => shop_name) 
shop.brands << Brand.create(:name => brand_name) 

또는 다른 방법으로 주위 : 당신이 만든 단체로 문제를

+0

OP가 수동으로 ID를 삽입해야하는 유스 케이스는 무엇입니까? 내가 제안 할 수있는 한, accepts_nested_attributes_for가 트릭을 할 것입니다. –

+0

사실 브랜드의 속성은 상점에서 전달되지 않으므로 accepts_nested_attributes_for는 작동하지 않습니다. 상점에서 브랜드 데이터를 전달하면 accepts_nested_attributes_for를 통해 브랜드와 상점이 연결됩니다. – Srushti

관련 문제