1

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?

Evo_x
  • 2,997
  • 5
  • 24
  • 40

1 Answers1

4

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.

Community
  • 1
  • 1
steakchaser
  • 5,198
  • 1
  • 26
  • 34
  • if its a caching problem you could also use a cache buster .. e.G a random part in the url – john Smith Feb 18 '14 at 17:08
  • It's not a cache problem. Can I pass the random variable generated via JS as a local in my render call? – Evo_x Feb 18 '14 at 17:12
  • Why can't you create the random number on the controller and pass it to the view? – Paulo Henrique Feb 18 '14 at 17:13
  • @StephanS. the render call only happens once on the server-side. If you look at the source of that page after it has loaded the full contents of the partial will be in the `append` function and not the actual render call anymore. – steakchaser Feb 18 '14 at 20:38