试图CSV记录上传到城市模型数据库,收到错误UnknownAttributeError CSV
ActiveRecord::UnknownAttributeError in PagesController#import
unknown attribute 'country ' for City. (City.create! row.to_hash)
CSV:
name country general_info1 general_info2 (etc)
Toronto Canada This is a test (nil)
上传观点
<%= form_tag upload_path, multipart: true do %>
<%= file_field_tag :file %>
<%= submit_tag "import" %>
<% end %>
路线:
post '/upload' => 'pages#import'
PagesController
def import
City.import(params[:file])
end
城市模型
def self.import(file)
logger.info "__________________"
logger.info file.inspect
logger.info file.path
logger.info "__________________"
CSV.foreach(file.path, headers: true) do |row|
City.create! row.to_hash
#puts '&&&&&&&&&&&&&&&&&&&&&&&' + row[1]
logger.info row.inspect
end
模式
ActiveRecord::Schema.define(version: 20160513090837) do
create_table "cities", force: :cascade do |t|
t.string "name"
t.string "country"
t.string "general_info1"
t.string "general_info2"
t.integer "happiness_rating"
t.integer "family_safety_rating"
t.string "family_safety_info"
t.integer "bike_hobby_rating"
t.string "bike_hobby_info"
t.integer "accountant_rating"
t.integer "accountant_shortage_rating"
t.string "accountant_shortage"
t.integer "accountant_avg_salary"
t.integer "graphic_designer_rating"
t.string "graphic_designer_shortage"
t.integer "graphic_designer_avg_salary"
t.integer "journalist_rating"
t.string "journalist_shortage"
t.integer "journalist_avg_salary"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
许多在此先感谢
答案:
CSV.foreach(file.path, {headers: true, header_converters: :symbol}) do |row|
City.create!(row.to_hash)
end
看到这个...可有人请解释为什么头必须是一个符号?谢谢 – daveasdf