如何避免通过重定向更改模型的数据

时间:2017-08-09 15:03:30

标签: ruby-on-rails ruby stateless

我的home_controller.rb看起来像这样:

class HomeController < ApplicationController
  def index
    @post_a = Post.where(title: 'a').sample
    @post_b = Post.where(title: 'b').sample
  end

index.html.erb就像这样:

<div>
   <%= @post_a.title %>
   <%= @post_b.title %>
</div>

刷新页面后,@post_a.title@post_b.title会发生变化。

有没有办法阻止数据被刷新或重定向更改?

2 个答案:

答案 0 :(得分:0)

变量包含您为其分配的值。当您使用随机记录(使用sample)时,查询结果是从数据库中获取的随机记录,因此这两个变量的值是 random 。< / p>

如果您希望将可预测记录分配给@post_a@post_b,则需要更新查询以获取所需记录。

例如,按ID获取:

@post_a = Post.find(1)

答案 1 :(得分:0)

这是RESTful的基本属性,因此无状态的系统就像Rails创建的系统一样,对请求的响应无法直接访问在另一个响应中完成的操作。除响应之外要访问的所有内容都必须保存在某个地方,通常是数据库。

为了从第二个响应访问您在第一个响应中设置的变量的值,标准方法是在session中保存信息。您也许可以阅读this

鉴于您正在使用重定向,另一种方法是在调用重定向时将值作为参数传递给路径帮助器方法。而不是做:

redirect_to foo_bar_path

你可以这样做:

redirect_to foo_bar_path(post_a_id: @post_a.id, post_b_id: @post_b.id)

然后在重定向目标位置的控制器操作中,您可以访问@post_apost_b的ID params[:post_a_id]params[:post_b_id]