nohayeye
nohayeye

Reputation: 2024

How to chain model creates

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

How do I create an Dealer, an Article and a Unit at the same time?

First thing I tried was something like this, but it seams to be totally wrong.

@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) 

Upvotes: 0

Views: 235

Answers (1)

PinnyM
PinnyM

Reputation: 35531

Firstly, you're missing a units association on your Article class. You'll need to fix that:

has_many :units

By 'at the same time', I'm assuming you mean in the same database transaction. You can try this:

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

Upvotes: 1

Related Questions