Tuesday, August 21, 2007

Multiple Ruby objects

Ruby on Rails - Editing multiple rows of data on one form

I think I may have poorly chosen my first application to learn Rails or maybe not...

I am trying to set up some simple profit-loss reports for our store Natures Paws.

Working with a legacy schema with Rails has been challenging but, I still have found Rails pleasing to use. Tonight, I ran into a situation where, I wanted to be able to update multiple line items in an order and update the model with this data. Rails was able to handle this so easily once I figured out what to do. (Thanks to the params hash dump shown on a Ruby exception page, I was able to figure out what I was doing wrong).

So, if a view has some code, iterating through some line items (each a row in a database table), like so


<% for @line in @profit_report.report_lines %>

<%= h @line.product_name %>
<%= text_field("line[]", 'wholesale_price', :size => 4, :maxsize => 4, :onchange => 'updateWholeSaleTotal(this.value);') %>
<%= text_field("line[]", 'ourshipping_price', :size => 4, :maxsize => 4) %>
<%= h @line.customer_price %>
<%= h @line.customer_shipping_price %>
<%= text_field("line[]", 'usps_price', :size => 4, :maxsize => 4) %>
<%= h @line.commission_paid %>


<% end %>


Then the Controller code can then update each lines in the model like so...


@params[:line].each do |idx, line|
report_line = ReportLine.find(idx)
report_line.update_attributes(line)
end


I have to say that is pretty sweet.

No comments:

analytics