mysql - Rails 4 迁移 : Create mysql table with primary key but without auto_increment

标签 mysql ruby ruby-on-rails-4 ruby-on-rails-4.2

可能重复How to turn off auto_increment in Rails Active Record

rails 新手,我想创建一个 fm_zipcodeszipcode 作为主键,但我不需要额外的 auto_increment。我尝试了不同的方法,但没有一个对我有用,并且 auto_increment 没有反射(reflect)在 db/schema.rb 文件中。

create_table :fm_zipcodes, :primary_key => :zipcode do |t|
  t.integer :state_id, null: false
  ..
end

关闭答案https://stackoverflow.com/a/17960388/1093542

最佳答案

我会做这样的事情:

# in your migration
def up
  create_table :fm_zipcodes, id: false do |t|
    t.integer :zipcode, null: false
    # ...
  end
  add_index :fm_zipcodes, :zipcode, unique: true
end

# in your FmZipcode model
self.primary_key = 'zipcode'

关于mysql - Rails 4 迁移 : Create mysql table with primary key but without auto_increment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35196983/

相关文章:

php - 当状态改变时发送电子邮件通知?

php - 不总结整列

ruby-on-rails - 编辑文本时 Rails 控制台运行速度异常缓慢

ruby-on-rails - 如何根据多对多关系选择用户子集?

mysql - 如果某些列是可选的,用覆盖索引查询一堆列的最佳方法是什么?

php - 使用 php 自动递增 LIMIT

ruby - 我如何在 ruby​​ 2.5 中解码或解析 "multipart/form-data"并使用参数获取哈希值

ruby - 如何使用 rbenv 在不使用 sudo 的情况下全局安装 gem?

jquery - Rails 4 自动完成 gem 问题,遵循示例

ruby-on-rails - 第三方集成代码放置的 Ruby on Rails 最佳实践