Hello Humans!
Finally, I cracked it.
The secret to longevity and you don't die of software bugs/blocks.
SECRET: "Never Give Up!"
I wrote a custom route to a custom action in my controller and made it work. +1.
In the config/routes.rb file above,
I have declared a member route for shipments to add the inventories I wanted to be shipped and routed it to "ShipmentsController#add_inventory".
We need to pass the IDs of both the shipment and the inventory to be added to the said shipment. We pass it using the path we set in the routes in show.html.erb.
<div class="container-fluid">
<h4><%= @shipment.name.upcase %></h4>
<strong>Shipment Inventories:</strong>
<ol>
<% @shipment.inventories.each do |si| %>
<%= si.name.upcase %><br>
<% si.items.each do |si_item| %>
<li>
<span>
<strong>Name:</strong>
<%= si_item.name %>
|
<strong>Count:</strong>
<%= si_item.count %>
</span>
</li>
<% end %>
<% end %>
</ol>
<h5>ALL INVENTORIES:</h5>
<% @inventories.each do |inventory| %>
<strong><%= inventory.name.upcase %></strong><br>
<strong>Items:</strong><br>
<ol>
<% inventory.items.each do |item| %>
<li>
<span>
<strong>Name:</strong>
<%= item.name %>
|
<strong>Count:</strong>
<%= item.count %>
</span>
</li>
<% end %>
</ol>
<%= link_to "Add to shipment", add_inventory_shipment_path(@shipment, inventory) %>
<% end %>
</div>
As you can see in the line,
<%= link_to "Add to shipment", add_inventory_shipment_path(@shipment, inventory) %>
We are passing the objects @shipment and inventory as required params in the action :add_inventory.
As shown above, the controller is passed parameters :id and :shipment_id. It was confusing because :shipment_id isn't the :id of Inventory and the object should be,
@inventory = Inventory.find(params[:id])
and not:
@inventory = Inventory.find(params[:shipment_id])
considering the shipment_id is nil as we haven't added the shipment_id to @inventory yet. But since we pass the inventory ID as the parameter :shipment_id it should work and find the Inventory of shipment_id: "7" as in my project.
Then we use the in-built Rails method :update_attribute(key, value) and update it with:
@inventory.update_attribute(:shipment_id, @shipment.id)
Now we can retrieve inventories of shipment & it's items using,
@shipment.inventories
# ...
@shipment.inventories.last.items
Like shown below:
There is a lot of re-factoring to do. And a lot of learning as well. RIP.
That's it for today. Thank you all for checking in. Please subscribe to my newsletter if you'd like. Thank you again.
Bye!
Love,
M.
liked_the_post == true ? comment and share : comment and share