我想用字符串主键创建表。
Product_Category模型:
class Product_Category < ActiveRecord::Base
self.primary_key = "product_category_name"
self.table_name = "product_category"
belongs_to :shop_category
validates :product_category_name, uniqueness: true
end
迁移:
class CreateProductCategory < ActiveRecord::Migration
def change
create_table :product_category, id: false do |t|
t.string :product_category_name, null: false
t.string :shop_category_id
t.boolean :disable_product_category
end
execute "ALTER TABLE 'product_category' ADD PRIMARY KEY ('product_category_name')"
end
end
但在 rake db:migrate 之后,我收到了:
rake db:migrate
?== CreateProductCategory: migrating ==========================================
-- create_table(:product_category, {:id=>false})
-> 0.0381s
-- execute("ALTER TABLE 'product_category' ADD PRIMARY KEY ('product_category_name')")
rake aborted!
An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: near "PRIMARY": syntax error: ALTER TABLE 'product_category' ADD PRIMARY KEY ('product_category_name')E:/androcommerce/admin_backend/db/migrate/20140414145913_create_product_category.rb:8:in `change'
C:in `migrate'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
我不明白为什么。语法是真的。
答案 0 :(得分:1)
试试这个:
execute "ALTER TABLE product_category ADD PRIMARY KEY (product_category_name);"
编辑:让我们尝试另一种方法。只需在create table选项中设置主键,然后抛弃execute命令。
{
:id => false,
:primary_key => :product_category_name
}
如果您有与ProductCategory相关的任何关联,请将外键设置为product_category_name。例如:
belongs_to :product_category, foreign_key: product_category_name