Reputation: 45
I cannot solve the following problem Any help or suggestion is appreciated
Agent collects orders for Product on a paper going from one Shop to another in his Region.
At the end of the day, he inserts the quantity of each Product to each Shop.
Each Shop orders more than 4 types of products.
I need to design to be able to bulk insert.
<table>
<tr>
<td>Shop1</td>
<td>Product1</td>
<td>Product2</td>
<td>Product3</td>
<td>Product4</td>
etc...
</tr>
<tr>
<td>Shop2</td>
<td>Product1</td>
<td>Product2</td>
<td>Product3</td>
<td>Product4</td>
etc...
</tr>
etc...
</table>
In the browser it needs to look as below
Upvotes: 0
Views: 465
Reputation: 9895
One approach could be to use a custom form model. This is a pretty good guide on the subject. This may not be perfect, but should get you on the right track at least. All credit to the following (slightly modified for your question) code goes to Sam Slotsky from the blog linked above. Read the post for more detail about each piece.
Here's the custom form model:
class ProductForm
include ActiveModel::Model
attr_accessor :products
def products_attributes=(attributes)
@products ||= []
attributes.each do |i, product_params|
@products.push(Product.new(product_params))
end
end
end
Here's the controller:
class ProductsController < ApplicationController
def new
@product_Form = ProductForm.new(products: [Product.new])
end
def create
@product_form = ProductForm.new(params[:product_form])
if @product_form.save
flash[:notice] = "Created products"
redirect_to root_path
else
flash[:notice] = "There were errors"
render :new
end
end
end
Here's the view:
<div>
<%= form_for @product_form, url: products_path, method: :post do |f| %>
<%= f.fields_for :products do |c| %>
<%= c.text_field :attr_1 %>
<%= c.text_field :attr_2
<%- # ... etc ... %>
<% end %>
<p>
<%= f.submit "Submit" %>
</p>
<% end %>
</div>
Upvotes: 1