Forum: Ruby on Rails Validate order lines on order creation (ActiveResource)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Tomasz B. (Guest)
on 2009-04-22 02:08
Hello,
I have order model that has many lines. I would like to create order
only when all order lines will be created:

require 'rubygems'
require 'activeresource'
class PurchaseOrder < ActiveResource::Base
  self.site = "http://admin:secret@localhost:23456"
end
o = PurchaseOrder.create(:account_ref => '123', :lines => [{ :code =>
"111" }, {:code => "222"}])
puts o.inspect

If I add validation that code has to be <200, then the PurchaseOrder
should never be created.

The problem is, I am not aware of the rails way of doing it :)

I started directing towards doing custom validation before after_create
with this code:

class PurchaseOrder < ActiveRecord::Base
  has_many :purchase_order_lines

  attr_accessor :new_lines

  def lines=(_lines)
    @new_lines ||= []
    _lines.each do |_line_params|
      puts _line_params.inspect
      @new_lines << PurchaseOrderLine.new(_line_params)
    end
  end

  after_create :store_lines

  def store_lines
    new_lines.each do |line|
      line.purchase_order = self
      line.save!
    end
  end
end

However this does not seem elegant. How can I do it, so that the
creation is done in one call and less custom code needs to be written?

Regards,
Tomasz Bak
This topic is locked and can not be replied to.