1

我正在尝试在我的 rails 应用程序中生成随机数据。但是我遇到了十进制金额的问题。我收到一条错误消息,说范围值不正确。

while $start < $max
        $donation = Donation.new(member: Member.all.sample, amount:  [BigDecimal('5.00')...BigDecimal('200.00')].sample,
                                 date_give: Random.date_between(:today...Date.civil(2010,9,11)).to_date,
                                 donation_reason: ['tithes','offering','undisclosed','building-fund'].sample )
        $donation.save
        $start +=1
      end
4

1 回答 1

4

如果您想要两个数字之间的随机小数,则 sample 不是要走的路。相反,请执行以下操作:

random_value = (200.0 - 5.0) * rand() + 5

另外两个建议:
1. 如果你实现了这个,很好,但它看起来不标准Random.date_between(:today...Date.civil(2010,9,11)).to_date
2.$variable表示 Ruby 中的全局变量,所以你可能不想要那个。

更新---真正获得随机日期的方法

require 'date'

def random_date_between(first, second)
  number_of_days = (first - second).abs
  [first, second].min + rand(number_of_days)
end

random_date_between(Date.today, Date.civil(2010,9,11))
=> #<Date: 2012-05-15 ((2456063j,0s,0n),+0s,2299161j)>
random_date_between(Date.today, Date.civil(2010,9,11))
=> #<Date: 2011-04-13 ((2455665j,0s,0n),+0s,2299161j)>
于 2012-11-22T02:52:23.740 回答