我想播種我的Products
並將它們分配到特定的User
和Store
。如何種子belongs_to關聯?
Product.rb
class Product < ActiveRecord::Base
belongs_to :user
belongs_to :store
def product_store=(id)
self.store_id = id
end
end
注:Store
belongs_to的Business
(:business_name
)
Seed.rb
這是我的基本設置:
user = User.create(:username => 'user', :email => '[email protected]')
store = Store.create(:business_name => 'store', :address => 'Japan')
我嘗試這些,但他們沒有工作:
# This gives random ID's ranging from 1 to 4425!?
user.products.create([{:name => "Apple", :product_store => Store.find_by_address('San Francisco, USA')}])
# This gives me undefined method 'walmart'.
user.store.products.create([ {:name => "Apple"} ])
有沒有一種方法來設置ID的,所以我可以聯想我Products
爲Store
和User
?
更新 -
我曾嘗試下面的答案,還是出來了成功。有誰知道另一種方式來做到這一點?
你指定一個類存儲的實例來STORE_ID ..的整數值:product_store = > Store.find_by_address('美國舊金山')。這是行不通的..你應該可以使用Store.find_by_address('Japan').id代替 – shadowbq 2012-10-25 20:55:14