实例变量未使用重定向设置
什么会导致我的实例变量@product没有为重定向设置/传递。 Product是ActiveModel对象,而不是ActiveRecord。 更具体地说,@ product变量没有出现在redirect_to(new_services_path)或redirect_to(home_path)页面中。 由于@product变量需要在我的页脚中填充每页上的表单。
Application_controller:
class ApplicationController < ActionController::Base before_filter :set_product private def set_product @product ||= Product.new end end
Product_controller:
def new end def create @product = Product.new(params[:product]) if @product.category == "wheels" redirect_to(new_services_path) else redirect_to(home_path) end end
与此原始post相关的问题。 通过多个部分传递变量(轨道4)
实例变量不会在重定向上传递。
因此,在到达before_filter
时没有@product
对象,因此您每次只创建新的和空的Product
对象。
ActiveModel对象不能在会话之间保持不变,但您可以将属性保留在会话存储中并在before_filter中使用它
def set_product @product = Product.new(session[:product]) if session[:product] @product ||= Product.new end
在您的创建方法中,您将表单参数移动到会话中…
def create session[:product] = params[:product] set_product if @product.category == 'wheels' ---
请注意,我们在create方法中显式调用了set_product
,因为会话[:product]已经重新建立。
如果您想知道为什么实例变量丢失…在create方法中,您位于ProductController的实例中,并且该实例具有自己的实例变量。 当您重定向时,您正在指示rails创建一个其他(或相同)控制器的新实例,以及该全新控制器对象,它没有建立实例变量。
要添加到SteveTurczyn
的答案,您需要阅读有关面向对象的编程 。 在我这样做之后,所有的@instance
变量都变得更清晰了。
非常好的写作
Ruby是面向对象的,这意味着每次发送请求时,都必须调用所有相关对象 (类)来与之交互:
此请求的持续时间称为实例 。 重定向会调用新请求; 因此,您的各种类的新实例 。
这就是每次用户与新操作交互时必须调用新的@instance
变量的原因:
#app/controllers/your_controller.rb class YourController < ApplicationController def edit @model = Model.find params[:id] end def update @model = Model.find params[:id] #-> new request = new instance end end
–
因此,当你问…
@product
变量需要在我的页脚中填充每个页面上的表单。
您需要记住, 每次渲染动作时都会调用它。 你已经这样做了; 问题是你没有持久化数据:
#app/controllers/application_controller.rb class ApplicationController < ActionController::Base before_filter :set_product private def set_product @product ||= Product.new #-> after "create", params[:product] = nil (new instance) end end
@SteveTurczyn
在提到将数据放入会话时得到了它。 按照文档 ……
HTTP是无状态协议 。 会话使其成为有状态的。
Steve提到的解决方案适用于少量数据但是如何获取一些记录并使用redirect_to传递它。 会议不允许我们那么多空间。
我所做的是我将这些记录设置在flash对象中,当它重定向到页面时,flash为我成功地呈现了数据。
flash[:products] = @products redirect_to users_path
让我知道,它是如何工作的……