简体   繁体   English

Ruby on Rails-具有局部视图的实例变量的范围

[英]Ruby on Rails - Scope of Instance Variables with Partial Views

I do not understand how to use instance variable properly with partial views, I am hoping someone here can enlighten me. 我不明白如何在局部视图中正确使用实例变量,我希望这里的人能给我启发。 For example: 例如:

class MainController < ApplicationController

  def index
    @item_list = Item.find_all_item
  end

  def detail_display
    @current_selected = @item= Item.find(params[:id])
      redirect_to :action => :index
  end
end

detail_display is invoked when the user clicks on an item in the list. 当用户单击列表中的项目时,将调用detail_display The variable @current_selected is not available to the partial view invoked when the index is redirected to. 索引重定向到时,变量@current_selected不适用于调用的局部视图。 How can I remedy this? 我该如何补救?

Thank you 谢谢

When you do a redirect, the browser sends an entirely new request, so all of the data from the previous request is inaccessible. 进行重定向时,浏览器会发送一个全新的请求,因此无法访问前一个请求中的所有数据。 You probably don't want to be doing a redirect here; 您可能不想在这里进行重定向; no amount of scope will help you when you're looking at separate runs through your controller. 当您通过控制器查看单独的运行时,没有任何范围会帮助您。

Think about your design a little bit - what are you trying to do? 稍微考虑一下您的设计-您打算做什么? If the selection is something sticky, maybe it should go in the session. 如果选择有些棘手,则应该在会话中进行。 If the change is only in a partial, maybe you should use an Ajax call. 如果更改只是部分更改,则也许应该使用Ajax调用。 Maybe the solution is as simple as rendering the index template instead of redirecting to the index action. 也许解决方案就像呈现index模板一样简单,而不是重定向到index操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM