Redirection in Rails
I have a small question regarding rails. I have a search controller which s开发者_如何学JAVAearches for a name in database, if found shows the details about it or else I am redirecting to the new name page. Is there anyway after redirection that the name searched for to automatically appear in the new form page?
Thanks in advance.
You can use the ActionController::Flash to pass data between actions.
def search(searchedName)
# perform search on DB
flash[:searchedName] = searchedName
redirect_to new_name
end
def new_name
end
new_name.html.erb:
<% if flash[:searchedName] %>
<%= text_field_tag flash[:searchedName] %>
<% end %>
Well, let's say you are saving this 'name' entered by user on a variable named @name.
So, on the controller that do the action of search, you did something like:
if @name
...#action if the name was found
else
session[:name] = @name
...#here is the action you did to redirect
On the declaration of the method called (you said it was 'new') :
def new
@name = session[:name] if session[:name] #I don't know exactly if the condition is this one,
#but you have to confirm that the session was instatiated
session.delete(:name) #to don't let garbage
...#continuous the action of show the new page
#and on the page you have access to a variable @name, that have the name searched before.
精彩评论