我在我的seeds.rb文件中生成了许多嵌套对象,并且遇到了一个问题。所有对象都是正确创建的,除了绑定到父对象的属性之外。在以下文件中:
seeds.rb
accounts.each do |i|
80.times do |j|
type = types.sample
case (type)
...
end
t = AcctTransaction.new
t.account_id = i.id
t.transaction_type_id = type
t.description = description
t.amount = amount
# keep transaction in chronological order unless it's the first one
unless AcctTransaction.exists?(account_id: t.account_id)
t.date = rand(i.date_opened..Time.now)
else
t.date = rand(AcctTransaction.where(account_id: t.account_id).last.date..Time.now)
end
t.adjusted_bal = i.balance + t.amount
i.update_attribute :balance, t.adjusted_bal
t.save
account_transactions << t
end
endRake :seed无错误地运行,并生成每个帐户的80个事务(约12000个总事务)。唯一的问题是,为adjusted_bal ( AcctTransactions模型)和更新的余额值(帐户模型)生成的值是不正确的。它们只需反映当前余额+交易金额的计算。
我的计算或循环本身是否有问题,或者我是否使用错误的方法将这些计算值分配给它们各自的模型?我已经尝试了100种不同的方法,但没有运气。请帮帮忙。
它是Rails 4.1.8 /Ruby2.1.5。谢谢。
编辑
澄清. 种子文件的这一部分应该执行以下操作:
示例
第一次迭代:
第二次迭代:
(这样做80次)
希望这能让事情更清楚。谢谢
编辑(不正确)结果的屏幕剪辑.

从这个屏幕剪辑(放大)中可以看到,标题中的帐户余额是1073.62美元。在每个交易中,balance列(从acct_transaction模型中是列)正好是从1073.62美元中减去的金额--这意味着帐户余额从未改变过。
发布于 2015-04-12 14:12:34
我不知道你的代码出了什么问题,对我来说似乎没问题,但请允许我帮你清理一下,它也应该工作得更快,因为它可以减少查询,它可能会帮助你找出问题出在哪里。也许是lol
accounts.each do |account|
80.times do # no need for iterator
type = types.sample
case (type)
# ...
end
# this will save and insert the new transaction in the collection
# at the same time
# will save you the second query that updates the relation
account_transactions.create do |transaction|
transaction.account_id = account.id
transaction.transaction_type_id = type
transaction.description = description
transaction.amount = amount
transaction.adjusted_bal = account.balance + transaction.amount
# doing a first_or_initialize, will save you one query
# in loops where the record actually exist
transaction.date =
(t = AcctTransaction.where(account_id: t.account_id).first_or_initalize).persisted? ?
rand(account.date_opened..Time.now) :
rand(t.date..Time.now)
end
end
# save only once after the 80 loops, before moving to the next account
# could save you up to 80 queries in each loop
account.save
endhttps://stackoverflow.com/questions/29585524
复制相似问题