未知属性"id"导入csv到rails应用程序时 [英] Unknown attribute "id" when importing csv to rails app

查看:107
本文介绍了未知属性"id"导入csv到rails应用程序时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个csv导入我的应用程序,并且遇到路由错误"TableName的未知属性'id'"

到目前为止,我知道这应该是由于我的csv的列与我的表不匹配,但是事实并非如此.我很确定这与.csv中的列名是"id"有关,因为这可能是保留字,但是我尝试在create_table中设置id: false,但仍然出现错误./p>

我仍然掌握着红宝石的精髓,因此我们将不胜感激.谢谢!

模式:

class CreateContacts < ActiveRecord::Migration[5.2]
  def change
    create_table :contacts do |t|
      t.integer :id
      t.string :first_name
      t.string :last_name
      t.string :company
      t.string :email
      t.string :address1
      t.string :address2
      t.string :city
      t.string :state_long
      t.string :state
      t.string :phone

      t.timestamps
    end
  end
end

控制器:

require 'csv'

class ContactController < ApplicationController
  def index
  end

  CSV.foreach('app/data/contact_data.csv', :headers => true) do |row|
    Contact.create!(row.to_hash)
  end
end

解决方案

在Rails中,id是自动生成的,因此您无需在迁移文件中指定ID.您可以在迁移文件中删除以下行:

t.integer :id

I'm importing a csv to my app and I'm getting a routing error "unknown attribute 'id' for TableName"

I understand so far that this should be due to my csv having columns that don't match with my table, but this isn't the case. I'm pretty sure it has to do with my column name in the .csv being "id", as that might be a reserved word, but I tried setting id: false in my create_table and I still got an error.

I'm still getting the hang of ruby so any help would be appreciated. Thanks!

schema:

class CreateContacts < ActiveRecord::Migration[5.2]
  def change
    create_table :contacts do |t|
      t.integer :id
      t.string :first_name
      t.string :last_name
      t.string :company
      t.string :email
      t.string :address1
      t.string :address2
      t.string :city
      t.string :state_long
      t.string :state
      t.string :phone

      t.timestamps
    end
  end
end

controller:

require 'csv'

class ContactController < ApplicationController
  def index
  end

  CSV.foreach('app/data/contact_data.csv', :headers => true) do |row|
    Contact.create!(row.to_hash)
  end
end

解决方案

In Rails, id is generated automatically, so you don't need specify the id in the migration file. You can remove this line in migration file:

t.integer :id

这篇关于未知属性"id"导入csv到rails应用程序时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆