Machinist Blueprint when model belongs to 2 has_many associations

1.4k views Asked by At

Environment: Ruby 1.9.2, Rails 3.1, Machinist 2

I have a Transaction model which belongs to both an Account and Category.

class Transaction < ActiveRecord::Base
  belongs_to :account
  belongs_to :category

  validates_presence_of :account_id, :category_id
end

class Account < ActiveRecord::Base
  has_many :transactions
end

class Category < ActiveRecord::Base
  has_many :transactions
end

I would like to make Machinist blueprints for Account and Category that creates multiple transactions, like so:

Account.blueprint do
  name { "Account #{sn}" }
  transactions(3)
end

Category.blueprint do
  name { "Category Name #{sn}"}
  transactions(3)
end

Transaction.blueprint do
  date { Date.current }
  amount { "#{rand(100000)}.#{rand(100)}" }
  description { "Transaction description #{sn}"}
end

Since a Transaction requires both an Account and Category the above blueprints fail because when Account.make! is called the Transactions created don't have associated Categories and when Category.make! is called the Transactions created don't have associated Accounts. I've tried to manually create the transactions inside the Account and Category blueprints but I end up in infinite loops.

Any advice would be greatly appreciated!

Thanks!

1

There are 1 answers

0
d11wtq On

Try this.

Pass an Array of Hashes that could be passed to separate blueprints. Here's an example.

Account.blueprint do
  name         { "Accouunt#{sn}" }
  transactions { [{:amount => 10}, {:amount => 20}] }
end

If you don't want to pass any parameters to Transaction, just pass empty Hashes:

Account.blueprint do
  name         { "Accouunt#{sn}" }
  transactions { [{}] * 3 } # 3 transactions
end

You may need to explicitly pass the :category and :account options accordingly if you run into the same issue, but you can contain them to the blueprint.