【问题标题】:Machinist Blueprint when model belongs to 2 has_many associations模型属于 2 个 has_many 关联时的机械师蓝图
【发布时间】:2011-10-13 22:36:59
【问题描述】:

环境:Ruby 1.9.2、Rails 3.1、Machinist 2

我有一个同时属于 Account 和 Category 的 Transaction 模型。

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

我想为创建多个交易的帐户和类别制作机械师蓝图,如下所示:

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

由于交易需要帐户和类别,因此上述蓝图失败,因为当 Account.make!被称为创建的事务没有关联的类别,并且当 Category.make!被称为创建的交易没有关联的帐户。我尝试在 Account 和 Category 蓝图中手动创建交易,但最终陷入无限循环。

任何建议将不胜感激!

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby testing rspec machinist


    【解决方案1】:

    试试这个。

    传递可以传递给单独蓝图的哈希数组。这是一个例子。

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

    如果不想给Transaction传任何参数,就传空Hashes:

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

    如果遇到同样的问题,您可能需要相应地显式传递 :category:account 选项,但您可以将它们包含在蓝图中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多