【发布时间】:2015-02-25 00:13:48
【问题描述】:
我需要在 rails 4.1.8 应用程序中使用 14 位 bigInt 作为主键。使用 SO 上较早的帖子作为指导,我想出了以下内容来解决这个问题......
class CreateAcctTransactions < ActiveRecord::Migration
def change
create_table "acct_transactions", :id => false do |t|
t.integer :id, :limit => 8,null: false
t.integer "account_id",limit: 8,null: false
t.integer "transaction_type_id", null: false
t.datetime "date",null: false
t.text "description",limit: 255
t.decimal "amount",precision: 10, scale: 2, null: false
end
end
end
但是,这个方法并没有真正将“id”分配为主键,它只是另一个普通字段。另外,当我收到以下错误时...
Mysql2::Error: 字段 'id' 没有默认值:INSERT INTO
acct_transactions(account_id,amount,date,description,transaction_type_id) 值 (224149525446, 222.450361056561, '1970-12-18 00:00:00', '转会', 6)
当我尝试运行以下种子文件时...
account_transactions = []
accounts.each do |i|
80.times do |j|
type = types.sample
case (type)
...
end
t = AcctTransaction.new
t.id = SecureRandom.random_number(99999999999999) # 14-digit BigInt
t.account_id = accounts[j].id
t.transaction_type_id = type
t.date = Time.at((Time.now.month - 18) + rand * (Time.now.to_f)).to_date
t.description = description
t.amount = amount
t.save
account_transactions << t
end
end
迁移运行良好,但表不会播种并且 id 不是主要的。我犯了错误吗?或者有更好的方法吗?
非常感谢
【问题讨论】:
-
rails3 bigint primary key 的可能重复项
标签: mysql ruby-on-rails activerecord rails-migrations ruby-on-rails-4.1