问题
Question:
How I want to redirect to different path after create action, given if previous_page is ../reader/new goes to ../reader/blog/:id, whereas if previous_page is ../editor/new goes to ../editor/blog/:id.
Explaination:
I want to modify the controller actions so that it can redirect to different path depending on which page it comes from. For example, I have a reader, editor and blog model. Both reader and editor can create a blog.
Here is the original blogs_controller:
class BlogsController < ApplicationsController
def create
@blog = Blog.new(blog_params)
respond_to do |format|
if @blog.save
format.html { redirect_to @blog }
else
format.html { render :new }
end
end
end
private
def blog_params
params.require(:service).permit(:title, :content)
end
end
回答1:
You have a few options:
- use
redirect_to :backin the controller if all you need is redirecting back to the previous page - add some logic processing the HTTP referer, i.e. decide where to redirect based on
request.refererin the controller - pass the redirection info in a parameter to the
createaction, e.g. passparams[:redirect_to] = "reader"when coming from the "reader" page and decide where to redirect based on this parameter. You can even place the whole URI to redirect into the param and just redirect to it (but this approach is unsafe as params can be mangled by users).
Generally, I'd choose the third option (parameters) as you have the best control over the redirection process (the first two options rely on HTTP referer which can also be mangled by any visitor, thus are potentially unsafe).
来源:https://stackoverflow.com/questions/35897322/controller-redirect-to-different-paths-depending-on-previous-page