我想批量加载CSV用耙子任务文件在Ruby on Rails的5获得UnknownAttributeError在耙使用CSV,属性存在的Rails应用程序
我有一个简单的模型,这将是列表电影。我有轨应用程序运行,并可以成功地创建一个新的电影W/Web应用程序。当我运行rake任务时,出现UnknownAttributeError:未知属性“标题”的电影
这里是我的架构:
create_table "movies", force: :cascade do |t|
t.string "Title"
t.string "Genre"
t.string "Rating"
<snip>
end
这里是我的创建方法(直出脚手架...)
def create
@movie = Movie.new(movie_params)
respond_to do |format|
if @movie.save
format.html { redirect_to @movie, notice: 'Movie was successfully created.' }
format.json { render :show, status: :created, location: @movie }
else
format.html { render :new }
format.json { render json: @movie.errors, status: :unprocessable_entity }
end
end
end
这里是我的耙子任务:
desc "bulk load movies in the db"
task :upload_movies => [ :environment] do
require 'csv'
f = "#{Rails.root}/tmp/movies.csv"
raise "#{f} does not exist. Stoping import of movies" if !File.exists?(f)
CSV.foreach(f, :headers => true) do |row|
Movie.create!(row.to_hash)
end
end
当我通过应用程序添加电影,服务器控制台显示它正常工作是这样的:
(0.1ms) BEGIN SQL (1.3ms) INSERT INTO "movies" ("Title", "Genre", "Rating", "Lead", "Director", "Year", "Type", "Duration", "Theater", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING "id" [["Title", "the ballerina"], ["Genre", "sci fi"], ["Rating", "PG"], ["Lead", "random"], ["Director", "local"], ["Year", 2010], ["Type", "3D"], ["Duration", 90], ["Theater", "3/4"], ["created_at", 2016-12-24 15:05:21 UTC], ["updated_at", 2016-12-24 15:05:21 UTC]] (0.6ms) COMMIT Redirected to http://localhost:3000/movies/1
我的CSV文件的顶部看起来是这样的:
Title,Genre,Rating,Lead,Director,Year,Type,Duration,Theater
The Avengers: Age of Ultron 3D,Action,PG-13,Robert Downey Jr.,Joss Whedon,2015,3D,141,3/4
这里的耙任务的输出 - (我跑这个例子,只是让这个社区知道我的db是最新的...)
$ rake db:migrate
$ rake upload_movies
rake aborted!
ActiveModel::UnknownAttributeError: unknown attribute 'Title' for Movie.
/Users/ustonma/dev/stone/gl7movies/lib/tasks/movieUpload.rake:11:in `block (2 levels) in <top (required)>'
/Users/ustonma/dev/stone/gl7movies/lib/tasks/movieUpload.rake:10:in `block in <top (required)>'
Tasks: TOP => upload_movies
(See full trace by running task with --trace)
$
我在想什么? - 谢谢。
尝试更新我上传的使用小写字段标题的CSV文件。 rake任务中的结果相同:'$ rake upload_movies rake中止! ActiveModel :: UnknownAttributeError:电影的未知属性'标题'。 /Users/ustonma/dev/stone/gl7movies/lib/tasks/movieUpload.rake:11:in' /Users/ustonma/dev/stone/gl7movies/lib /tasks/movieUpload.rake:10:in 中的块' 任务:TOP => upload_movies (请参阅通过运行具有--trace的任务完整跟踪)' –
user2711286