Recently, I created a page displaying the number of Widgets a customer has. Below is the view written in Haml:
#available
= "Available widgets: #{@customer.widgets.unused.count()}"
(The "unused" scope in the model displays available widgets).
When a Customer redeems Widgets using a form with ":remote => true", some JavaScript dynamically adds a DIV to the page with animation and updates the model through the controller.
Check out the controller below:
def redeem
@customer = Customer.find(params[:customer_id])
number = params[:amount].to_i
unless @customer.widgets.unused.empty?
number.times do
@customer = Customer.find(params[:customer_id])
widget = @customer.widgets.unused.first # Grab first unused pass
widget.status = "Redeemed"
widget.save!
end
else
@pay = "true"
# customer.widgets.new
end
# redirect_to @customer
And here's the JavaScript (js.erb):
var number = <%= params[:amount] %>;
<% if @pay.eql? "true" %>
$("#widget-pay").modal('toggle');
<% else %>
while (number > 0) {
var item = $('<div class="widget-show">...</div>');
$('#allwidgets').isotope('insert', item);
number --;
}
<% end %>
Now, I am facing an issue where I need to update the "#available" DIV with the new Widget count. How can this be accomplished?
Options include reloading the page to fetch data from the model again or just updating the DIV. Unfortunately, neither seems achievable directly from the JavaScript.