Hi I’ve the following code:
def update_for_transport_document
# => DESCRIPTION:
# => Utilizzata nelle form di associazione di un warehouse ad una bolla
@wh_errors = Hash.new
if request.path.include? "ingress_transport_document"
session[:user_role] != "administrator" ?
@itd = IngressTransportDocument.filtered_by_registry(session[:registry_id]).find(params[:warehouse][:ingress_transport_document_id]) :
@itd = IngressTransportDocument.find(params[:warehouse][:ingress_transport_document_id])
@all_itd = IngressTransportDocument.all
logger.debug { "INGRESS_TRANSPORT_DOCUMENT_ID: #{@itd.id} " }
@warehouse = Warehouse.find(params[:warehouse][:id])
#check_warehouse_in_td(@all_itd,@warehouse)
@all_itd.each do |td|
td.warehouses.each do |whs|
logger.debug {"TD WAREHOUSES:#{whs.id} && #{@warehouse.id}"}
if whs.id == @warehouse.id
@ok = 'ciccia'
break
break
end
end
end
logger.debug {"OK:#{@ok} "}
if @ok != 'ciccia'
@itd.warehouses << @warehouse
else
logger.debug{"NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO"}
end
respond_to do |format|
format.html { redirect_to(@itd) }
format.xml { head :ok }
end
else
session[:user_role] != "administrator" ?
@etd = EgressTransportDocument.filtered_by_registry(session[:registry_id]).find(params[:warehouse][:ingress_transport_document_id]) :
@etd = EgressTransportDocument.find(params[:warehouse][:ingress_transport_document_id])
logger.debug { "TEST" }
logger.debug { "EGRESS_TRANSPORT_DOCUMENT_ID: #{@etd.id}" }
@warehouse = Warehouse.find(params[:warehouse][:id])
logger.debug { "WAREHOUSE_ID: #{@warehouse.id}" }
@etd.warehouses << @warehouse
respond_to do |format|
format.html { redirect_to(@etd) }
format.xml { head :ok }
end
end
end
and I’d want that @warehouse can be append to @itd(@etd).warehouses only if the same warehouse is not present in others ingress(egress)transport documents.
My issue is that using this code any warehouse can be append to @itd(@etd).warehouses both if warehouse is present in another transport document neither if it’s a new one not associated to any itd/etd.
Where’s the mistake?
It’s really hard to find bug in your code.
I will not try to guess which single line makes errors, instead I will give you few hints:
There is general rule in Rails environment
fat models - skinny controllers. For your code it means: leave only the minimum over code generated by scaffolding. All business logic move into models. You may ask why: there are few reasons: you can reuse your code, it’s much easier to make unit test against model than controller.I would really encourage you to try build unit test for logic in your model. It is much efficient than debugging. However debugger is still powerfull tool, I use debugger from Rubymine. Debugger gives you possibility to inspect all variables state in line-by-line application execution.
One thing in your code: overuse of
?operatorIs less readable than: