2013-01-01 64 views
0
class Article < ActiveRecord::Base 
    attr_accessible :console, :ean, :title, :title_spaceless 
    has_many :dealers, :through => :units 
end 

class Dealer < ActiveRecord::Base 
    attr_accessible :adress, :name, :website 
    has_many :articles, :through => :units 
    validates :name, :uniqueness => { :case_sensitive => false } 
end 

class Unit < ActiveRecord::Base 
    attr_accessible :article_id, :dealer_id, :note, :price 
    belongs_to :article 
    belongs_to :unit 
end 

如何創建經銷商,物品和單位在同一時間?如何鏈接模型創建

我試過的第一件事就是這樣,但它的接縫是完全錯誤的。

@dealer = Dealer.find_or_create_by_name("Surugaya") 
@dealer.article.create(:title => game.content, :title_spaceless => game.content.delete(' '), :console => "SNES").unit.create(:article_id => @dealer.article.article_id, :units_id => @dealer.article.unit_id, :price => game.price) 

回答

1

首先,你錯過了你的Articleunits關聯。你需要解決這個問題:

has_many :units 

通過「在同一時間」,我假設你在同一個數據庫事務的意思。你可以試試這個:

Dealer.transaction do 
    @dealer = Dealer.find_or_create_by_name("Surugaya") 
    @article = @dealer.articles.create!(
     :title => game.content, 
     :title_spaceless => game.content.delete(' '), 
     :console => "SNES" 
) 
    @unit = @article.units.create!(:price => game.price) 
end