Ruby on Rails: embed ActiveRecord object into JavaScript
I have /invoices/ controller and @service object.
When /services/1/invoices/new is called, a new @invoice form is created.
The @service there is used to get quantity, price and discounts.
I want to use @service.discounts in my Javascript to be able to update the @invoice.price field in the form everytime the quantity is being changed.
How do I do this?
Tried开发者_C百科:
invoices.coffee.erb
service = <%= @service.to_json %>
Doesn't work, because javascript is generated / cached before @service object is available.
Something like
service = <%= Service.find(1).to_json %>
Obviously works, but it's the same problem: I need the object to be changed dynamically, according to /services/ID/invoices/new page
If the object is retrieved in the action, and rendered in the controller, there shouldn't be an issue: all you're doing is multiplying the price by the quantity, which is pure JavaScript.
If you're trying to update based on information not rendered in the template, then you'd probably want to use Ajax to get the updated data from the server, then make use of it in the template (or return already-rendered HTML, or a JavaScript fragment, etc.)
精彩评论