无法更新使用Populator和Faker gems生成的数据

时间:2011-03-13 22:17:32

标签: ruby-on-rails ruby-on-rails-3

我使用Ryan Bates的populator gem和faker gem来填充我的开发数据库,​​每个帖子有2k用户,10k帖子和1 ... 2k票。我成功生成了数据但忘记更新Post模型中的字段voting_count。这是与帖子相关的票数的反小块。

现在,我正在尝试返回并更新数据库,以便为每个帖子对象提供准确的值。但是,当我使用这个小方法时,这似乎不适用于“rails console”环境:

def post_updater
  Post.all.each do |p|
    p.votes_count = p.votes.count
    p.save!
  end
end

我调用post_updater并且没有错误。但是,当我输入这个

a = Post.first
a.votes_count
=> 0

如果我使用Post.last也是如此。我认为这可能只是一个侥幸,也许有0票的Post对象(反正不应该是真的,但我们假设......)。我仍然可以这样做:

a = Post.first
a.votes_count = a.votes.count
a.save!
=> true
a.votes_count
=> 667
Post.find(a.id)
=> #<Post id: 2175, post_content: "Eveniet adipisci doloremque laborum ea sit sequire...",
   user_id: 2180, category_id: 5, created_at: "2010-04-14 20:06:21",
   updated_at: "2011-03-13 22:01:22",votes_count: 0, flags_count: nil, rank: nil>

有人能说清楚这里发生了什么吗?我知道populator gem以某种方式绕过验证以快速保存大量数据。尽管如此,这与我能做到的一样多。

1 个答案:

答案 0 :(得分:1)

我唯一能想到的是数据库级别的异常。也许你的数据库期望为votes_count提供另一种类型的数据,或者这可能是一个计算值。