Safwan Marwan
Safwan Marwan

Reputation: 94

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

Upvotes: 4

Views: 3809

Answers (1)

Matouš Bor&#225;k
Matouš Bor&#225;k

Reputation: 15944

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).

Upvotes: 5

Related Questions