Redirecting users after destroy

Posted by mathee on Stack Overflow See other posts from Stack Overflow or by mathee
Published on 2010-05-06T01:58:22Z Indexed on 2010/05/06 3:08 UTC
Read the original article Hit count: 273

Filed under:
|

I have 3 models: Questions, Answers, and Profiles (I know, it should be called "Users"). When you view a question Q, I query the database for the answers to Q. (They are linked by id.) In the view, the current user has the option to delete his answer by clicking on the destroy link displayed next to his answer:

%table
  %tr
    %td
      Answers:
  - @answers.each do |a|
    %tr
      %td
        - @provider = Profile.find(a.provider)
        %i
          #{h @provider.username} said:
        %br
        #{h a.description}
      %td
        = link_to 'View full answer', a
      %td
        - if a.provider == @profile.id
          #{link_to 'Delete my answer', a, :confirm => 'Are you sure?', :method => :delete}

The problem is that when the user clicks on the destroy link, it redirects to the /answers/index. I want it to redirect to /questions/Q. What's the best way to do this?

I know that there's a redirect_to method, but I don't know how to implement it when I want to redirect to an action for a different controller. It also needs to remember the question from which the answer is being deleted.

I tried passing something like :question_id in link_to as:

#{link_to 'Delete my answer', a, :confirm => 'Are you sure?', :question_id => @question.id, :method => :delete}

In AnswersController#destroy:

  def destroy
    @answer = Answer.find(params[:id])
    @answer.destroy

    respond_to do |format|
      format.html { redirect_to(answers_url) }
      format.xml  { head :ok }
    end

    @question = Question.find(params[:question_id])
    redirect_to question_path(@question)
  end

The :question_id information is not passed to the destroy method, so I get this error:

Couldn't find Question without an ID

To confirm, I added a puts call before Question.find, and it returned nil.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about haml