gpt4 book ai didi

ruby-on-rails - Rails 迁移创建带有基于字符串的主键的表

转载 作者:太空宇宙 更新时间:2023-11-03 16:59:20 26 4
gpt4 key购买 nike

通过主键是字符串而不是 int 的迁移在 Rails 中创建表的正确方法是什么?

我已经尝试按照@oldergod 在下面的答案中建议的那样设置 primary_keybaz 似乎仍然设置为 int:

class CreateFoos < ActiveRecord::Migration
def change
create_table :foos, primary_key: 'baz' do |t|
end
end
end

更新

我试过了

class CreateFoos < ActiveRecord::Migration
def change
create_table :foos, primary_key: false do |t|
t.string :baz
end
end
end

这让我更接近了一点,但仍然缺少列上的 PRIMARY 索引。我试过 add_index :foos, :baz, type: :primary 但这会产生以下错误:

SQLite3::SQLException: near "primary": syntax error: CREATE primary INDEX "index_foos_on_baz" ON "foos" ("baz")/Users/kyledecot/.rvm/gems/ruby-1.9.3-p392/gems/sqlite3-1.3.8/lib/sqlite3/database.rb:91:in `initialize'

在查看 http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_index_options 之后,这似乎应该可行

最佳答案

如果是字符串有什么不同?查看create table文档。

create_table :foos, primary_key: 'baz' do |t|
t.column :baz, :string
end

Also note that this just sets the primary key in the table. You additionally need to configure the primary key in the model via self.primary_key=. Models do NOT auto-detect the primary key from their table definition.

关于ruby-on-rails - Rails 迁移创建带有基于字符串的主键的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18960212/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com