vendredi 26 août 2016

Create multiple records with a simple form on Rails

I'm creating an inventory app, and one of the features is to change the stock inventory in bulk, so when you go to the Stocks link, it will show you a full list of items with 2 fields, INs and OUTs, once the user completes this and saves, it will be stored in the stock table (which has IN OUT and item_id fields, and created_at and updated_at)

So far i have been struggling with this, since all the examples i have been looking focus more on the item itself and not on the stock part (on my case)

Here is what i have so far:

this is the _form.erb on the stocks folder

<% @items.each do |item| %>
 <%= form_for item do |f| %>
  <%= f.fields_for :stocks, [Stock.new] do |stock| %>
   <%= f.label item.nombre %>
   Altas <%= stock.text_field :altas %>
   Bajas <%= stock.text_field :bajas %>
   <%= stock.hidden_field :items_id, :value => item.id %>
   <% end %>
  <%= f.submit %>
 <% end %>
<% end %>

I didnt do anything other than the scaffold on the controllers

and the models has this: stock.rb

class Stock < ActiveRecord::Base
 belongs_to :items
end

item.rb

class Item < ActiveRecord::Base
 has_many :stocks
 attr_accessible :nombre, :espesor, :material, :quantity
 accepts_nested_attributes_for :stocks
 attr_accessible :stocks_attributes
 self.per_page = 50

 protected
end

So far running this code, will show me each item name with both fields but also an update button for each item, and running the code will give me an error in the controller

unknown attribute 'item_id' for Stock.

and the following param is what im getting:

{"utf8"=>"✓",
"_method"=>"patch",
   "authenticity_token"=>"xAdfWBvf4MdkeiZ8xR5ElkNaMMTB5ySt1C9nCG5iGw2hwgDs1MJ2luLH2slvaEEIQBgjac4+RkxZIg6InIbZ1A==",
"item"=>{"stocks_attributes"=>{"0"=>{"altas"=>"7",
"bajas"=>"8",
"items_id"=>"4"}}},
"commit"=>"Update item",
"id"=>"4"}

so its only storing one value and not all 4 (on this case are 4 items)

Aucun commentaire:

Enregistrer un commentaire