Note that there are some explanatory texts on larger screens.

plurals
  1. PORails 3.2 Simplify Controller with Model Methods on has_many :through
    primarykey
    data
    text
    <p>Most questions I've seen with skinnying up controllers deals with a simple model relationships. My question is if you're updating a many to many form with multiple parameters and their associated arrays, how do you simplify the task by moving it all to a model method? For example take a look at the ridiculously large controller below. What's the simplest way of dealing with this unholy mess? I'm not looking for a syntactically perfect answer but need a general consensus on a direction to go with this. </p> <pre><code>def update @shipment = Shipment.joins(:products).find(params[:id], :readonly =&gt; false) @shipment.update_attributes(params[:shipment]) @shipment_products = params[:product_shipments] @product_shipment_array= array_from_hash(@shipment_products) @shipment.product_shipments.each do |product_shipment| product_shipment.update_attributes(:qty_shipped =&gt; params[:product_shipments][product_shipment.id.to_s][:qty_shipped], :pickup_item =&gt; params[:product_shipments][product_shipment.id.to_s][:pickup_item]) end @product_shipment_array.each do |p| if p['old_pickup_item'] == "true" and p['pickup_item'].to_i==0 @difference = (p['qty_shipped'].to_i) Product.mark_open_shipment(@difference, p['product_id']) elsif p['old_pickup_item'] == "false" and p['pickup_item'].to_i==1 @difference = -(p['old_qty_shipped'].to_i) Product.mark_open_shipment(@difference, p['product_id']) else @difference = -(p['old_qty_shipped'].to_i - p['qty_shipped'].to_i) Product.mark_open_shipment(@difference, p['product_id']) end end respond_with @shipment, :location =&gt; shipments_url end </code></pre> <p>and in my model I want to declare a model method something like this</p> <pre><code>Class Shipment &lt; ActiveRecord::Base . . . def update_shipment_attributes #all business logic end end </code></pre> <p>In the hopes of getting my controller down to something like this or something similar:</p> <pre><code>def update @shipment = Shipment.joins(:products).find(params[:id], :readonly =&gt; false) @shipment.update_attributes(params[:shipment]) @shipment_products = params[:product_shipments] Shipment.update_shipment_attributes respond_with @shipment, :location =&gt; shipments_url end </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload