首页 > 解决方案 > rand has the same value when wrapped inside erb tag

问题描述

I have a new rails app, with a controller Page. The root path is set to 'page#index'.

The app/views/page/index.html has this code:

<h1>Page#index</h1>
<p>Find me in app/views/page/index.html.erb</p>

<script>
    setInterval(() => {
        console.log(<%= rand %>)
    }, 1000)
</script>

Which is truely a bad practice, but I am just curious to know why the console.log(<%= rand %>) line prints the same number every time?

标签: ruby-on-rails

解决方案


The template is rendered once. If you look at the source of the page you will see one fixed number in the JS code. Reload the page and it is a different number.

If you want a different number every time the JS function is executed you need to do it in JS:

setInterval(() => {
  console.log(Math.random())
}, 1000)

推荐阅读