未知属性"id"导入csv到rails应用程序时 [英] Unknown attribute "id" when importing csv to rails app
问题描述
我正在将一个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屋!