我有 2 个模型Order has_many line_items
和line_item belongs_to order
. 订单已创建,文件导入表单在订单展示表单上。我正在使用 roo gem 进行 CSV 导入,但如果有其他解决方案,我不必这样做。电子表格中的每一行都是一个新的 line_item,但我需要为每一行保存 order_id。我对所有解决方案持开放态度。
订单/show.html.erb
<%= form_tag import_line_items_path, multipart: true do %>
<%= file_field_tag :file %>
<%= submit_tag "Import" %>
<% end %>
line_items_controller.rb
def import
LineItem.import(params[:file])
redirect_to root_path, notice: "Products imported."
end
def edit
end
def create
@line_item = LineItem.new(line_item_params, :order_id => :order_id)
respond_to do |format|
if @line_item.save
format.html { redirect_to @line_item, notice: 'Line item was successfully created.' }
format.json { render :show, status: :created, location: @line_item }
else
format.html { render :new }
format.json { render json: @line_item.errors, status: :unprocessable_entity }
end
end
end
line_item.rb
class LineItem < ActiveRecord::Base
require 'csv'
belongs_to :order, inverse_of: :line_items
def self.import(file)
spreadsheet = Roo::Spreadsheet.open(file.path)
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
line_item = find_by(id: row["id"]) || new
line_item.attributes = row.to_hash
line_item.order_id = @order
puts @order
line_item.save!
end
end
end
这是我使用此代码时遇到的错误...
Validation failed: Order must exist