2013-02-27 63 views
1

后的主键,我不是很确定问题所在,但是当试图创建一个(通用)玩笑(模型)我得到以下错误:的Rails似乎没有随机部署

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 
+0

你为什么要这么做? – 2013-02-27 16:51:59

回答

2

你的关键是太大。您只能在该ID字段中放置一个32位(带符号)的整数。不知道为什么你想创建自己的主键,但不管怎么样,试试这个:

self.id = SecureRandom.random_number(1000_000_000) 

顺便说一句(2^32)/ 2 -1 = 2147483647

+0

现货,谢谢!将在4分钟内接受=) – ZirconCode 2013-02-27 16:58:36

+1

没问题,但我不知道为什么你要创建自己的主键?你可以让MySQL做它的事情,并为你创造它们。无论如何,很乐意帮助 – rainkinz 2013-02-27 17:05:13

+0

啊,我希望他们以特定的方式分配id,随机化只是一个占位符=) – ZirconCode 2013-03-01 13:49:33