Skip to content

Instantly share code, notes, and snippets.

@nowk
Created September 23, 2011 01:47
Show Gist options
  • Save nowk/1236566 to your computer and use it in GitHub Desktop.
Save nowk/1236566 to your computer and use it in GitHub Desktop.
An eh solution for SO Question#7400657.rb
class PurchaseOrderTest < ActiveSupport::TestCase
context "when PurchaseOrder exists" do
should "use the existing PurchaseOrder" do
original = PurchaseOrder.create! :purchase_order_no => "abcde", :note => "Original"
new_po = PurchaseOrder.create! :purchase_order_no => "abcde", :note => "New"
assert_equal 1, PurchaseOrder.all.size
assert_equal "Original", new_po.note
end
end
context "SalesTransaction" do
should "allow SalesTransactions to be created through anaf" do
original = PurchaseOrder.create! :purchase_order_no => "abcde", :note => "Original"
new_po = PurchaseOrder.create :purchase_order_no => "abcde",
:sales_transactions_attributes => [
{:note => "Sale 1"},
{:note => "Sale 2"}
]
assert_equal 1, PurchaseOrder.all.size
assert_equal original.note, new_po.note
assert_equal 2, new_po.sales_transactions.size
end
end
end
class PurchaseOrder < ActiveRecord::Base
has_many :sales_transactions, :foreign_key => "po_purchase_order_no",
:primary_key => "purchase_order_no"
before_validation :check_for_exisitng_po # maybe only on create?
accepts_nested_attributes_for :sales_transactions
private
def check_for_exisitng_po
existing_po = PurchaseOrder.find_by_purchase_order_no(self.purchase_order_no)
if existing_po
self.id = existing_po.id
self.reload # don't like this, also will overwrite new attrs
@new_record = false # hmm...
end
true
end
end
class SalesTransactionTest < ActiveSupport::TestCase
context "PurchaseOrder" do
should "allow PurchaseOrders to be created through anaf" do
original = PurchaseOrder.create! :purchase_order_no => "abcde", :note => "Original"
sale = SalesTransaction.create! :note => "Sale 1",
:purchase_order_attributes => {:purchase_order_no => "abcde", :note => "New"}
assert_equal 1, PurchaseOrder.all.size
assert_equal original.note, sale.purchase_order.note
end
end
end
class SalesTransaction < ActiveRecord::Base
belongs_to :purchase_order, :foreign_key => "po_purchase_order_no",
:primary_key => "purchase_order_no"
accepts_nested_attributes_for :purchase_order
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment