Question

I render a partial in my view like this:

<script>
$(document).ready(function(){
  $('#add_shipping_address').click(function(e){
    $('#shipping_addresses').append("<%= escape_javascript(render :partial => 'shipping_address' ) %>");
  });
});
</script>

The partial renders fine but in my partial I got a random variable

<% random_id = rand(9999999) %>

The strange thing is every time I render the partial via click on that button the random variable is the same, like it gets generated once and then just gets repeated. Is that a normal behaviour and if so, what can I do to avoid this?

Was it helpful?

Solution

The content for the partial is rendered once on the server side and then inserted into the DOM X times on the client-side, this is why the random value is always the same. You can either:

  1. Generate the random value using JS (see Generating random whole numbers in JavaScript in a specific range?)
  2. Call a server-side action to render and insert another partial
  3. Make some sort of server-side JSON API that produces random values

NOTE (not the root cause of the above issue, but worth mentioning): If you are using some kind of cache (like varnish), partial content can remain unchanged even on new requests, In this case, you could move the generation of the random number to the controller.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top