Thursday, April 21, 2011

rails: specify the HTTP verb in a redirect_to

Hi

Here's a basic overview of my domain:

  • a user has a list of courses
  • the user can "select" a course. The corresponding action is invoked with the PUT verb, stores the course_id in a session variable and redirects to the "show" action of the selected course.
  • when the user has only 1 course available, I want to redirect him directly to the only course available (and invoke the "select" method before, of course).

From there, i see 2 options:

  1. Keep the "select" action when the user clicks the link and add a new action for when the selection is automatic... but that doesn't look very DRY (even if I could refactor some code)
  2. call the PUT action from the controller itself... but I haven't found how (is it even possible)?

Any alternative is welcome :)

Thanks for your help.

P.

From stackoverflow
  • In the courses controller:

    def index
      @courses = Course.all
      if @courses.length == 1 #if only one course
        @course = @courses[0] #get that course
        session[:course_id] = @course.id #set the session
        redirect_to :action => "show", :param => "#{@course.id}" #redirect
      end
      respond_to do |format|
        format.html
        format.xml  { render :xml => @line_items }
      end
    end
    
    Pierre : Hi, thanks for the suggestion. I wanted to avoid duplicating the session[] part, but if there's no other choice, i think it will be a necessary evil. I'll perhaps make it a standalone method. Thanks! P.
    iano : Pierre, try: def show @course = Course.find(session[:course_id] instead of def show @course = Course.find(params[:id]) and you should be able to get rid of the param in the redirect_to line

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.