I want to write up a very simple javascript calculator in rails which multiplies the quantity of an input field by a number stored in a rails variable (@item.base_price)
So, on the javascript/coffeescript side of things, it’s crudely this:
# app/assets/javascript/items.js.coffee
$ ->
$('#item_quantity').change ->
quantity_val = $(this).val()
$('#total_amount').html(quantity_val * <%= I_WANT_@ITEM.BASE_PRICE_HERE %>)
I’m aware of how I can do this via an ajax call on each change() call, but I figure there has to be an elegant, hopefully unobtrusive rails way which doesn’t hit the server each time.
Any suggestions very appreciated
If you are using rails 3.1 you can take advantage of the assets pipeline to do some pre-processing on the javascript files before you serve them up. To do this just change the file extension from:
to
then you can add ruby to your javascript just like in your view with
<%= %>tags. The only gotcha you might run into, is that your items.js file will be served to every request to any of your app’s controller methods. So its best to write a helper method that will return the value only if the instance variable is initializedFor example in items_helper.rb
EDIT: more about assets pipeline here:
http://guides.rubyonrails.org/asset_pipeline.html