I am trying to build an estimate form that supports multiple line items. After completing an estimate line item by filling in the following fields:
- properties
- height
- letter_quantity
I would like to query a database table to get a unit price to multiply by letter_quantity and display the line item's cost. My thought is to execute the query and display the line item's cost onBlur from the letter_quantity field.
Here is my form:
<%= nested_form_for @estimate do |f| %>
<%= f.label :date %><br />
<%= f.text_field :date %><br />
<%= f.label :job_name %><br />
<%= f.text_field :job_name %><br />
<%= f.fields_for :items do |builder| %>
<%= builder.label :properties %><br />
<%= builder.text_field :properties %><br />
<%= builder.label :height %><br />
<%= builder.text_field :height %><br />
<%= builder.label :letter_quantity %><br />
<%= builder.text_field :letter_quantity %><br />
<%= builder.link_to_remove "Remove this item" %>
<% end %>
<%= f.link_to_add "Add a item", :items %>
<%= f.submit "Add item" %>
<% end %>
I would like to use the general jQuery ajax function to call a function that executes the query and returns the cost back to the form. Here is the basic template:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
class ItemsController < ApplicationController
def calculateCost
#Execute SQL query here
SELECT unit_price
FROM CostData
WHERE properties = form.properties
AND height = form.height
#Return unit_price x form.letter_quantity to form
end
end
Most importantly, how do I setup the jQuery Ajax function to call the calculateCost function? I have been searching Google and cannot find an example of this.
Secondarily, how do a setup the query and return functionality in the calculateCost function? Any help with these questions will be greatly appreciated.