Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controller redirect to different paths depending on previous page

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
like image 212
Safwan Marwan Avatar asked Oct 23 '25 15:10

Safwan Marwan


1 Answers

You have a few options:

  • use redirect_to :back in 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.referer in the controller
  • pass the redirection info in a parameter to the create action, e.g. pass params[: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).

like image 146
Matouš Borák Avatar answered Oct 25 '25 03:10

Matouš Borák



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!