如何链模型创建

时间:2013-01-01 22:37:00

标签: ruby-on-rails

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 个答案:

答案 0 :(得分:1)

首先,您在units课程中错过了Article个关联。你需要解决这个问题:

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