Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 访问实例变量_Ruby On Rails_Ruby On Rails 3_Model View Controller_Controller - Fatal编程技术网

Ruby on rails 访问实例变量

Ruby on rails 访问实例变量,ruby-on-rails,ruby-on-rails-3,model-view-controller,controller,Ruby On Rails,Ruby On Rails 3,Model View Controller,Controller,我只是想寻求一些关于在其类中访问实例变量的澄清(如果这是非常基本的,我深表歉意) 我的例子是,我有一个配方控制器,其中我有很多动作,但特别是我有一个索引和一个显示动作 def index @q = Recipe.search(params[:q]) @q.build_condition end @q根据通过我的搜索表单传递的参数搜索我的配方模型 我想在另一个页面上显示结果(稍后将查看AJAX选项),所以在我的显示操作中,我可以这样做吗 def show @searchresults = @

我只是想寻求一些关于在其类中访问实例变量的澄清(如果这是非常基本的,我深表歉意)

我的例子是,我有一个配方控制器,其中我有很多动作,但特别是我有一个索引和一个显示动作

def index
@q = Recipe.search(params[:q])
@q.build_condition
end
@q根据通过我的搜索表单传递的参数搜索我的配方模型

我想在另一个页面上显示结果(稍后将查看AJAX选项),所以在我的显示操作中,我可以这样做吗

 def show
 @searchresults = @q.result(:distinct => true)
 end
我认为这是正确的,但如果不是的话,我会在某个地方出错。有人能提出建议或提供一些建设性的建议吗


谢谢

您的对象或类应具有以下方法:

  • @foo.instance\u variables
    -这将列出
    @foo
  • @foo.instance\u variable\u get
    -这将获取
    @foo
    • 例如:
      @foo.instance\u variable\u get(“@bar”)
      -这将为
      @foo
      获取名为
      @bar
      的实例变量的值

您的对象或类应具有以下方法:

  • @foo.instance\u variables
    -这将列出
    @foo
  • @foo.instance\u variable\u get
    -这将获取
    @foo
    • 例如:
      @foo.instance\u variable\u get(“@bar”)
      -这将为
      @foo
      获取名为
      @bar
      的实例变量的值

不,您不能像这样使用实例变量,因为它们都有不同的操作,并且会因不同的请求而被调用

然而,以下方法将起作用

def index
  @q = Recipe.search(params[:q])
  @q.build_condition
  show
end

def show
  #Following line will work as we are calling this method in index 
  #and so we can use instance variable of index method in the show methos 
  @searchresults = @q.result(:distinct => true)
end

不,您不能像这样使用实例变量,因为它们都有不同的操作,并且会因不同的请求而被调用

然而,以下方法将起作用

def index
  @q = Recipe.search(params[:q])
  @q.build_condition
  show
end

def show
  #Following line will work as we are calling this method in index 
  #and so we can use instance variable of index method in the show methos 
  @searchresults = @q.result(:distinct => true)
end

谢谢你的回答,例如,如果我把搜索结果实例变量放在结果操作中,我只会在我的索引中调用结果..我想你已经为我澄清了这里的问题谢谢你的回答,例如,如果我把search results实例变量放在一个results操作中,我只会在我的索引中调用results。你认为你已经为我澄清了吗