Rails - 如何刷新页面而不重新加载它? [英] Rails - How do I refresh a page without reloading it?

查看:326
本文介绍了Rails - 如何刷新页面而不重新加载它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rails - 如何刷新网页而不重新载入?

Rails - How do I refresh a page without reloading it ?

我正在建立一个应用程式,每当使用者前往该网页时,该应用程式会显示随机数字(随机记录),但问题是当使用者

I'm building an app which has a function that gives out a random number (random record) every time people go to that page, but the problem is that when user goes to that page, a random number is given but that number will change again if the user refresh the page.

即使在用户刷新页面时,如何保留该随机数字或返回该页面,随机数保持不变。

How do keep that random number even when user refresh the page or comes back to that page, the random number stays the same.

我想在浏览器中禁用刷新功能,这将阻止用户刷新页面,从而阻止他们更改随机数,但在研究后,它看起来像一个好主意,禁用刷新功能。

I'm thinking disabling the refresh functionality in browsers which will stop users from refreshing the page hence stop them from changing the random number but after researching, it looks like it is a good idea to disabling the refresh functionality.

有没有其他方法来实现它?

Is there any other methods to achieve it?

我试过了

#posts_controller.rb    

def new
       @random = cookies[:stuff] ||= Stuff.random
end

并调用 @ random.content 在我看来,因为我只想要的内容 Stuff 模型,第一次是好的,但当我刷新页面,它给我 undefined方法contentfor#< Stuff:0x0000010331ac00>:String 发生了什么事情?

and call @random.content in my view since I want only the content of the Stuff model, the first time is fine but when I refresh the page, it gives me undefined method 'content' for "#<Stuff:0x0000010331ac00>":String What's going on?

推荐答案

p>您可以在控制器操作中执行此操作:

You could do this in your controller action:

# ex. app/controllers/index_controller.rb
def index
  session[:random] ||= rand(10000)
end

这将生成一个0到10000之间的随机数,并将其保存在用户的会话,仅 (如果之前尚未存在)。

This would generate a random number between 0 and 10000 and save it in the user's session, only if it wasn't already present before. This means that it will be the same for each specific user until he closes his browser.

如果您想在关闭浏览器后仍然保留内容,您可以改用 Cookie

If you want persist even after closing the browser then you could use cookies instead:

cookies[:random] ||= rand(10000)

您可以用您想要的任何自定义方法替换 rand(10000)调用。

You can replace the rand(10000) call by whatever custom method you want.

这篇关于Rails - 如何刷新页面而不重新加载它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆