2010-12-11 44 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

難道這些協會有道理?你會添加其他關聯嗎?

問題2

我想在db/seeds.db數據庫預填充。

添加ShopBrand我做的:

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

什麼是添加Product最恰當的方法是什麼?我真的需要手動插入shop_idbrand_id值嗎?如果商店和新創建產品的品牌尚不存在,它們是否會自動添加到數據庫中?

回答

5

的總體思路與你所做的協會是執行此操作:

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

或周圍的其他方式。如果您不想手動創建連接模型,則不必手動創建連接模型。

編輯:下面是關於您在下面的評論的演示。

設置遷移。

$ ./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

謝謝,但主要問題是關於插入「產品」... – 2010-12-11 07:06:23

+1

您嘗試過嗎?插入產品正是代碼所要做的。 – jdl 2010-12-11 16:03:53

+0

感謝您的努力!我不明白爲什麼'shop.brands << brand'增加了一個產品。你能詳細說明一下嗎?你如何定義這個產品的'name'和'price'? – 2010-12-13 04:00:35

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) 

請首先家長應創建那麼孩子這樣的頭腦,在插入數據首先創建店鋪和品牌,然後創建產品

希望,這可能解決您的問題

+0

當OP必須手動插入ID時,有哪些用例?據我可以建議,'accept_nested_attributes_for'將會訣竅。 – 2010-12-11 08:17:30

+0

其實品牌的屬性沒有在商店中傳遞,所以accept_nested_attributes_for將不起作用。如果您在店內傳遞品牌數據,那麼通過accepting_nested_attributes_for將在品牌和商店之間創建關聯 – Srushti 2010-12-11 08:39:32