有点凌乱,我在这里试图让它发挥作用。我有一个带有产品数据库的商店。我得到的是一个包含 3 列和 500 多个条目的 CSV 文件,ts_code cost_price 和 sell_price。
所以我需要一个我可以运行的任务来查找所有与 ts_code 匹配的产品,然后更新这些产品的 cost_price 和 sell_price。
我试图编辑我用来首先导入产品的任务,如下所示。
原始任务
require 'csv'
desc "Imports a CSV file into an ActiveRecord table"
task :import, [:filename] => :environment do
CSV.foreach('csv/vow.csv', :headers => true) do |row|
Spree::Product.create!(row.to_hash)
end
end
我希望这样的事情会起作用,但我现在被困住了。
require 'csv'
desc "Imports a CSV file into an ActiveRecord table"
task :update, [:filename] => :environment do
CSV.foreach('csv/vow.csv', :headers => true) do |row|
a = Spree::Product.find_by(:ts_code)
Spree::Product.update_all!(a, row.to_hash)
end
end
我也知道我需要告诉它要更新哪些列,但我不确定将它们放在哪里,比如成本和销售价格。如果有人可以提供帮助,那就太好了。
仍然试图以某种方式让它工作,接下来我尝试的是这个但得到一个错误未定义的方法 find_by。不知何故,语法是错误的,不确定我有多接近。
require 'csv'
desc "Imports a CSV file into an ActiveRecord table"
task :update, [:filename] => :environment do
CSV.foreach('csv/recharge_pricing.csv', :headers => true) do |row|
product = find_by(ts_code: row["ts_code"]) || new
parameters = ActionController::Parameters.new(row.to_hash)
product.update(parameters.permit(:cost_price,:price))
product.save!
end
end