I have 2 models Order has_many line_items
and line_item belongs_to order
. The order has been created and the file import form is on the order show form. i am using roo gem for CSV import, but I do not have to if there is another solution. Each row in the spreadsheet is a new line_item but I need to save the order_id for each line. I'm open to all solutions.
orders/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
This is the error I'm getting with this code...
Validation failed: Order must exist
You will have to pass the order
to import
action and self.import
methods. For example:
orders/show.html.erb
<%= form_tag import_line_items_path, multipart: true do %>
# Send order_id via hidden_field_tag
<%= hidden_field_tag :order_id, params[:id] %>
<%= file_field_tag :file %>
<%= submit_tag "Import" %>
<% end %>
line_items_controller.rb
def import
order = Order.find(params[:order_id])
LineItem.import(params[:file], order)
redirect_to root_path, notice: "Products imported."
end
line_item.rb
def self.import(file, order)
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.id
puts order
line_item.save!
end
end