Ismail Degani
Ismail Degani

Reputation: 887

Can HTTP redirects be accomplished without an extra request/response?

I'm writing a Rails app where I have two methods, a "list" and a "query". Here's a simplified version:

class ApplicationController < ActionController::Base
    def query
        # query based on user-form text in params[:q]
        @list = Product.where(Product.arel_table[:description].matches("%#{params[:q]}%"))
        if @list.count == 1
          redirect_to :action => 'list', :id => @list[0].id
        end
    end

    def list
        @item= Product.find(params[:id])
    end
 end

By far the most common user pattern is to enter a search that yields a single product. When this happens, I want the url to redirect to the restful

http://myurl/list/:id

rather than

http://myurl/query?q=search-query. 

But in the above code, I'm hitting the database twice to get the same record, and creating 2 http requests/responses for every query. Not the end of the world, but I was wondering if there's a better way. (I already have the model object in-hand when I run the query)

Is there a clean way to render the list action's view from the query action and tell the browser the new URL without an extra request/response?

Upvotes: 0

Views: 50

Answers (1)

troelskn
troelskn

Reputation: 117517

Not within the constraints of the http protocol.

Upvotes: 1

Related Questions