问题
I have two different ways to access the url "localhost:3000/childrens/new".
I have a drop down in childrens/new page and when the user selects an option through the drop down, it shows the different partials using ajax to call the childrens#new method.
- accessing the childrens new page from url "localhost:3000/parents"
- accessing the childrens new page from url "localhost:3000/parents1"
After the children have been successfully created, the user should be redirected to the relevant url (either localhost:3000/parents or localhost:3000/parents1)
回答1:
There are more than one way of how you can achieve this.
One solution would be to store the referrer inside of the session/cookie when the childrens/new is requested: (inside children_controller)
def new
session['children_new_referrer'] = request.env["HTTP_REFERER"]
#....YOUR CODE....
end
And then using that referrer value stored in session/cookie to redirect appropriately:
def create
#.....YOUR CODE....
if @child.save
format.html {redirect_to (session['children_new_referrer'] || parents_path)}
#.....YOUR CODE....
end
where @child is the object which I assume you are building with the parameters, and parents_path is being defined through your routes. Feel free to adjust these two based on your needs.
An alternative solution would be to not use sessions, but instead save the referrer uri/path inside of the children/new form page itself. This alternative has the benefit of making the solution session/request scope independent with handling the requirement of storing the referral uri/path within the page scope.
回答2:
Store the value in session like session[:last_request]
in parent
After create children redirect it to session[:last_request] || session[:return_to]
and after that clear the session[:last_request]
回答3:
Do something like this
def create
redirect_to :back
end
redirect_to :back should come after save.
回答4:
Pass the referrer as a parameter in the link. I would much prefer this solution to using the session store.
<%= link_to "New child", new_child_path(referrer: @parent.id) %>
.. or whatever you want to call it. Then you can inspect params[:referrer]
. You're not wanting to persist data across a 'session', so why use the session store.
回答5:
request.url
in your controller gives the url you are asking for. So,
def create
if @child.save
redirect_to request.url
end
end
will do the job perfectly
来源:https://stackoverflow.com/questions/17040221/rails-how-to-save-the-requested-url