UnknownAttributeError csv [英] UnknownAttributeError csv
问题描述
试图将csv记录上传到City模型数据库中,但出现错误
trying to upload csv record into City model database, getting error
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
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
非常感谢
answer:
CSV.foreach(file.path, {headers: true, header_converters: :symbol}) do |row|
City.create!(row.to_hash)
end
推荐答案
首先,如果City
模型的create!
方法预期出现在cities
表中的field
不存在,则出现ActiveRecord::UnknownAttributeError
.确保它在那里.
First of, ActiveRecord::UnknownAttributeError
occurs if the field
that City
models's create!
method is expecting to be present in cities
table is absent. Make sure its there.
有人可以解释为什么标头必须是符号吗?
can somebody please explain why the header needs to be a symbol?
在红宝石中解析CSV时,通常会以Hash
es的集合形式获取数据.在以下示例中,您可能已经注意到,所有Hash
的keys
都在重复,并且它们都是String
数据.在Ruby
中,每个String
实例都占用单独的内存空间.
When you parse CSV in ruby, you normally get the data as collection of Hash
es. In the following example you might have noticed that the keys
to all the Hash
es are repeating and they are String
data. In Ruby
every String
instance occupies separate memory space.
csv.to_a.map {|row| row.to_hash }
# => [{"Year"=>"1997", "Make"=>"Ford", "Model"=>"E350", "Description"=>"ac, abs, moon", "Price"=>"3000.00"}, {"Year"=>"1999", "Make"=>"Chevy", "Model"=>"Venture \"Extended Edition\"", "Description"=>"", "Price"=>"4900.00"}, {"Year"=>"1999", "Make"=>"Chevy", "Model"=>"Venture \"Extended Edition, Very Large\"", "Description"=>nil, "Price"=>"5000.00"}, {"Year"=>"1996", "Make"=>"Jeep", "Model"=>"Grand Cherokee", "Description"=>"MUST SELL!\nair, moon roof, loaded", "Price"=>"4799.00"}]
说字符串computer
占用8 bytes
.如果我定义此字符串1000,000
次,它将占用我RAM的8MB
.
Say string computer
occupies 8 bytes
. if I define this string 1000,000
times, it will occupy 8MB
of my RAM.
现在,如果您使用header_converters: :symbol
,它将调用to_sym
方法,该方法现在将keys
定义为symbol
s.
Now if you use header_converters: :symbol
, this will invoke to_sym
method which will now define the keys
as symbol
s.
csv = CSV.new(body, :headers => true, :header_converters => :symbol)
csv.to_a.map {|row| row.to_hash }
# => [{:year=>"1997", :make=>"Ford", :model=>"E350", :description=>"ac, abs, moon", :price=>"3000.00"}, {:year=>"1999", :make=>"Chevy", :model=>"Venture \"Extended Edition\"", :description=>"", :price=>"4900.00"}, {:year=>"1999", :make=>"Chevy", :model=>"Venture \"Extended Edition, Very Large\"", :description=>nil, :price=>"5000.00"}, {:year=>"1996", :make=>"Jeep", :model=>"Grand Cherokee", :description=>"MUST SELL!\nair, moon roof, loaded", :price=>"4799.00"}]
符号有何特色?
符号可提高内存效率,并且检索速度非常快.如果您定义符号:computer
1000,000
次,它将仅占用8Bytes
内存.
Symbol is memory efficient and retrieval is very fast. if you define symbol :computer
1000,000
times it will only occupy 8Bytes
of memory.
此说明如何解决我的问题?
您的CSV文件可能有成千上万行数据要转换为Hash
.因此,要使此过程更快且内存效率更高,请使用header_converters: :symbol
You CSV file might have thousands of lines of data to be converted to Hash
. So to make this process faster and memory efficient, you use header_converters: :symbol
有关更多信息,请参见此内容. http://ruby-doc.org/stdlib-2.0.0/libdoc/csv/rdoc/CSV.html#HeaderConverters
See this for more info http://ruby-doc.org/stdlib-2.0.0/libdoc/csv/rdoc/CSV.html#HeaderConverters
这篇关于UnknownAttributeError csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!