Undefined save method when using dynamic finders in rake task
I have a simple rake task importing records from a CSV file and saving them into the database.
require 'csv'
namespace :import do
task :items => :environment do
CSV.foreach(Rails.root.to_s + '/public/data/items.csv', :headers => true) do |开发者_开发问答row|
@item_id = row[1]
if item_id
i = Item.find_or_create_by_item_id(@item_id)
i.update_attributes(
:item_id => @item_id,
:category => row[2],
:price => row[3],
)
i.save
end
end
end
end
When I run it I get the following error.
rake aborted!
undefined method `save' for []:ActiveRecord::Relation
This was working fine and I have other rake tasks using dynamic finders on the same model in the same way which work fine. I can't figure out what changed or what is causing this. Any ideas would be greatly appreciated.
You have if item_id
. Should that be @item_id
? Also, update_attributes
automatically saves the record. You don't need to call save()
. Remove that line and see if that gets rid of the error.
As a side note, why do you have an attribute for Item called item_id
? It would be a lot better just to use id
unless you have a really good reason not to.
精彩评论