【问题标题】:How to create composite-primary-key in rails 4如何在 Rails 4 中创建复合主键
【发布时间】:2016-03-10 05:03:54
【问题描述】:

请帮我将此 PostgreSQL 表转换为 Rails 迁移文件和模型

CREATE DATABASE ip2location WITH ENCODING 'UTF8'; \c ip2location

CREATE TABLE ip2location_db1(
  ip_from integer(10) NOT NULL,
  ip_to integer(10) NOT NULL,
  country_code character(2) NOT NULL,
  country_name character varying(64) NOT NULL,
  CONSTRAINT ip2location_db1_pkey PRIMARY KEY (ip_from, ip_to)
);
  • 我想创建 Rails 模型来检索数据吗

【问题讨论】:

    标签: ruby-on-rails postgresql rails-migrations composite-primary-key


    【解决方案1】:

    终于找到了可行的解决方案

     def change
      create_table :ip2_location_v4s, id: false do |t|
       t.integer :ip_from
       t.integer :ip_to
       t.string :country_code
       t.string :country_name
      end
    
      execute "ALTER TABLE ip2_location_v4s ADD PRIMARY KEY (ip_from, ip_to);"
    end
    

    这生成了我需要的 SQL 表

    -- 表:ip2_location_v4s

    -- 删除表 ip2_location_v4s;

    CREATE TABLE ip2_location_v4s
    (
     ip_from bigint NOT NULL,
     ip_to bigint NOT NULL,
     country_code character varying(2) NOT NULL,
     country_name character varying(64) NOT NULL,
     CONSTRAINT ip2_location_v4s_pkey PRIMARY KEY (ip_from, ip_to)
    ) 
    

    感谢@mohammad-shahadat-hossain 抽出宝贵时间

    【讨论】:

    • 我们如何将其表示为模型?
    【解决方案2】:

    用于迁移脚本

    class Iplocation2 < ActiveRecord::Migration
     def change
      create_table :ip2location_db1, id: false do |t|
        t.integer :ip_from 
        t.integer :ip_to
        t.string :country_code
        t.string :country_name
        t.timestamps
      end
     end
    end
    

    对于模型

    class ip2location < ActiveRecord::Base
      self.primary_keys = :ip_from,:ip_to
      validates :language_id, uniqueness: { scope: [:id] }
    end
    

    【讨论】:

    • 我刚刚创建了迁移文件 'code' class CreateIp2LocationV4s 8, :null => false t.integer :ip_to, :limit => 8, :null => false t.string :country_code, :limit => 2 ,:null => false t.string :country_name, :limit => 64, :null => false add_index :ip2_location_v4s, ["ip_from", "ip_to"], :unique => true end end end '
    • 你在创建迁移文件后运行rake db:migrate了吗?
    • 是的,但是我出错了,rake 中止了! StandardError: 发生错误,此迁移和所有后续迁移已取消:PG::UndefinedTable: ERROR: relationship "ip2_location_v4s" does not exist
    • 首先rake db:reset如果它不起作用然后运行rake db:drop db:create db:migrate db:seed
    • 谢谢,我会检查你的解决方案,仍然没有运气,可能是我的错误,让我们看看
    猜你喜欢
    • 1970-01-01
    • 2014-06-13
    • 2011-04-24
    • 1970-01-01
    • 2014-07-08
    • 2017-06-12
    • 1970-01-01
    • 2017-07-22
    相关资源
    最近更新 更多