Ruby on Rails - Scope of Instance Variables with Partial Views
-
03-07-2019 - |
Question
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.
The variable @current_selected
is not available to the partial view
invoked when the index is redirected to. How can I remedy this?
Thank you
Solution
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. Maybe the solution is as simple as rendering the index
template instead of redirecting to the index
action.