# Validate order lines on order creation (ActiveResource)

**URL:** <https://www.ruby-forum.com/t/validate-order-lines-on-order-creation-activeresource/166110>\
**Category:** Rails\
**Created:** [April 22, 2009, 12:08am UTC](https://www.ruby-forum.com/t/validate-order-lines-on-order-creation-activeresource/166110 "2009-04-22T00:08:05Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![linus](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/f4b2a3/32.png) [@linus](https://www.ruby-forum.com/u/linus)\
**Post date:** [April 22, 2009, 12:08am UTC](https://www.ruby-forum.com/t/validate-order-lines-on-order-creation-activeresource/166110/1 "2009-04-22T00:08:05Z")

</div>

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](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
