1

I want create table with string primary key.

Product_Category model:

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

Migration:

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

But after rake db:migrate I receive:

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)

I don't understand why. Syntax is true.

ViT-Vetal-
  • 2,431
  • 3
  • 19
  • 35
  • This answer should help you http://stackoverflow.com/questions/750413/altering-the-primary-key-in-rails-to-be-a-string/6714889#6714889 – Pavan Apr 15 '14 at 04:21

1 Answers1

1

Try this:

execute "ALTER TABLE product_category ADD PRIMARY KEY (product_category_name);"

EDIT: Let's try another approach. Simply set the primary key in your create table options and ditch the execute command.

 {
    :id => false,
    :primary_key  => :product_category_name
 }

And if you have any associations related to ProductCategory set the foreign key to product_category_name. Example:

belongs_to :product_category, foreign_key: product_category_name
rails4guides.com
  • 1,441
  • 2
  • 11
  • 8