实例变量未设置重定向 [英] Instance variable not set with redirect

查看:84
本文介绍了实例变量未设置重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是什么导致我的实例变量@product不能为重定向设置/传递的.产品是ActiveModel对象,而不是ActiveRecord.更具体地说,@ product变量未出现在redirect_to(new_services_path)或redirect_to(home_path)页面中.由于@product变量需要在我的页脚中的每一页上填充一个表格.

What would cause my instance variable @product to not be set/passed for the redirect. Product is an ActiveModel object, not ActiveRecord. to be more specific, the @product variable is not appearing in the redirect_to(new_services_path) or redirect_to(home_path) pages. As the @product variable need to populate a form in my footer that is on every page.

Application_controller:

Application_controller:

class ApplicationController < ActionController::Base 
  before_filter :set_product

  private

  def set_product
    @product ||= Product.new
  end
end

Product_controller:

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

与此原始帖子相关的问题. 通过多个部分传递变量(第4条)

Issue related to this original post.. Passing variables through multiple partials (rails 4)

推荐答案

实例变量未通过重定向传递.

Instance variables are not passed on a redirect.

因此,到达before_filter时没有@product对象,因此每次只是创建一个新的空Product对象.

Consequently, you have no @product object at the time you are reaching the before_filter and so you're just creating the new and empty Product object each time.

ActiveModel对象不能在会话之间持久化,但是您可以将属性保留在会话存储中,并在before_filter中使用

ActiveModel objects can't persist from session to session, but you can keep the attributes in your session store and use that in your before_filter

def set_product
  @product = Product.new(session[:product]) if session[:product]
  @product ||= Product.new
end

然后在您的create方法中,将表单参数移至会话...

And in your create method you move the form params to the session...

def create
  session[:product] = params[:product]
  set_product 
  if @product.category == 'wheels'
  ---

请注意,由于已经重新建立了session [:product],因此我们在create方法中显式调用了set_product.

Notice that we called set_product explicitly in the create method because the session[:product] had been re-established.

如果您想知道为什么实例变量丢失了……在create方法中,您位于ProductController的实例中,并且该实例具有自己的实例变量.重定向时,您正在指示Rails创建某个其他(或相同)控制器的NEW实例,并且该全新的控制器对象尚未建立实例变量.

In case you're wondering WHY the instance variable is lost... in the create method you are in an instance of ProductController and that instance has it's own instance variables. When you redirect, you are instructing rails to create a NEW instance of some other (or the same) controller, and that brand new controller object, it has no instance variables established.

这篇关于实例变量未设置重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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