【问题标题】:Overwriting the id column in a Rails table覆盖 Rails 表中的 id 列
【发布时间】:2012-03-31 10:04:19
【问题描述】:

我正在基于我已经拥有的数据构建一个应用程序,我从客户端获取它作为 .mdb 文件 (MS Access)。它由多个表 T1、T2、...、TN 组成。

到目前为止我所做的:将 Access 表转换为 CSV,通过脚本创建了我的 Rails 表 t1,但 ID 不正确 我想做的:为 T1 到 TN 的每个表创建一个 Rails 表 问题:我不知道如何摆脱默认的 Rails id 列,即自动递增

详情: 我有带有属性(t1_id、姓名、电子邮件、电话)的表 T1 假设我有 3 个元组: (3, Foo, foo@g.com, 0000) (9, Bar, bar@g.com, 1111) (32, Baz, baz@g.com, 2222) 正如我所拥有的,ID 不是一个整齐的序列 1、2、3 - 在某些时候一定有删除。 我知道如何使用 CSV 填充我的 Rails 表,使用这个脚本:

require 'csv'
CSV.foreach('./db/seeds/file.csv', headers: true) do |row|
    p row   #p = advanced toString
    p T1.create(id: row['\xEF\xBB\xBFT1ID'], first_name: row['FirstName'], phone: row['Phone'], email: row['Email'])
end

如您所见,我的 CSV 标头有点奇怪,我有一些 unicode 字符挂在那里... 无论如何,我的模型如下,取自 schema.rb :

create_table "t1", :force => true do |t|
  t.string   "first_name"
  t.string   "phone"
  t.string   "email"
  t.datetime "created_at",       :null => false
  t.datetime "updated_at",       :null => false
end

运行脚本后,我的表有以下元组,ID 错误:
(1, Foo, foo@g.com, 0000) (2, Bar, bar@g.com, 1111) (3, Baz, baz@g.com, 2222)

我怎样才能获得正确的 ID? 太棒了!

【问题讨论】:

    标签: ruby-on-rails-3


    【解决方案1】:

    基于this,您应该运行 Rails 迁移

    def up
       remove_column :t1, :id
    end
    

    【讨论】:

      【解决方案2】:

      无法访问 :id 列进行批量分配。试着把它分开:

      require 'csv'
      CSV.foreach('./db/seeds/file.csv', headers: true) do |row|
        p row   #p = advanced toString
        record = T1.new(first_name: row['FirstName'], phone: row['Phone'], email: row['Email'])
        record.id = row['\xEF\xBB\xBFT1ID']
        p record.save
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-10
        • 2022-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多