I have the following model:
create_table "mouldings", :force => true do |t|
t.string "suppliers_code"
t.datetime "created_at"
t.datetime "updated_at"
t.string "name"
t.integer "supplier_id"
t.decimal "length", :precision => 3, :scale => 2
t.decimal "cost", :precision => 4, :scale => 2
t.integer "width"
t.integer "depth"
end
When a user selects a moulding on a form I want to get the cost of the moulding by ajax and use it to get a generate a quote using javascript. Here is the select tag from the form:
<select id="order_item_moulding_1_id" name="order_item_moulding_1[id]">
<option value="">Select a moulding 1</option>
<option value="1">123 589 698</option>
<option value="2">897 896 887</option>
<option value="3">876 234 567</option>
</select>
Here is part of the javascript file:
$(document).ready(function () {
$('#order_item_moulding_1_id').change(function () {
var moulding_1_price = ;
});
});
How do I use Ajax to set the variable moulding_1_price?
If you wanted to do it in your rails controller via ajax, you’d just set the value of each option to the ID of the molding you were looking up, and send that to your controller with jQuery’s ajax method:
Then make sure you have a route set in your routes.rb file:
And in your yourMouldingsController, define a custom method:
By default, this will render ajaxMouldings.js.erb. So in your views, make sure you have a file with that name. That’s embedded javascript, so you can use it to replace some div on your page where you want that information to appear:
Obviously, you’ll want to throw in a few safeguards against bad data, etc… but that should get you on the right track.