我不确定问题出在哪里,但是在尝试创建(通用)笑话(模型)时出现以下错误:
ActiveRecord::RecordNotUnique (Mysql2::Error: Duplicate entry '2147483647' for key 'PRIMARY': INSERT INTO `jokes` (`content`, `created_at`, `id`, `rating`, `updated_at`) VALUES ('dsfgdsfgdfgd', '2013-02-27 16:33:12', 90650754896700, 0, '2013-02-27 16:33:12')):
app/controllers/jokes_controller.rb:141:in `create'
app/controllers/jokes_controller.rb:140:in `create'
当我尝试保存另一个时:
ActiveRecord::RecordNotUnique (Mysql2::Error: Duplicate entry '2147483647' for key 'PRIMARY': INSERT INTO `jokes` (`content`, `created_at`, `id`, `rating`, `updated_at`) VALUES ('dsfgdsfg', '2013-02-27 16:32:23', 29733688655250, 0, '2013-02-27 16:32:23')):
app/controllers/jokes_controller.rb:141:in `create'
app/controllers/jokes_controller.rb:140:in `create'
该错误提到我有一个重复的条目(主键 2147483647)。我只能创造一个笑话。在部署之前我从未遇到过这个问题,我能想到的唯一值得注意的变化是数据库类型,从 sqlite3 到 mysql2。
这是我的笑话模型中的重要代码位:
before_create :randomize_id
#...
validates :content, :presence => true
validates :content, :uniqueness => true
#...
private
def randomize_id
begin
self.id = SecureRandom.random_number(100_000_000_000_000)
end while Joke.where(:id => self.id).exists?
end