销毁后重定向用户

时间:2010-05-06 01:58:23

标签: ruby-on-rails haml

我有3个模型:问题,答案和个人资料(我知道,它应该被称为“用户”)。当您查看问题Q时,我在数据库中查询Q的答案。(它们通过id链接。)在视图中,当前用户可以选择通过单击其答案旁边显示的销毁链接来删除其答案:

%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}

问题是当用户点击destroy链接时,它会重定向到/ answers / index。我希望它重定向到/ questions / Q.最好的方法是什么?

我知道有一个redirect_to方法,但是当我想重定向到另一个控制器的动作时,我不知道如何实现它。它还需要记住正在删除答案的问题。

我尝试在link_to中传递类似:question_id的内容:

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

在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

:question_id信息没有传递给destroy方法,所以我收到了这个错误:

Couldn't find Question without an ID

要确认,我在puts之前添加了Question.find来电,并返回nil

我也尝试将问题ID存储在会话信息中。 AnswersController#destroy更改调用会话[:question_id]而不是params [:question_id]。但是,我得到了一个不同的错误:

Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".

我不确定如何解决错误。我应该在哪里放return

任何帮助都将不胜感激!!

1 个答案:

答案 0 :(得分:4)

在定义销毁行为的操作中,您只需在完成时添加redirect_to。

redirect_to可以使用任何标准的url / rout辅助方法:

假设您有一个问题控制器以及相关的路径和操作,您可以使用:

redirect_to question_path(@question)

在上面编辑的案例中,您需要确保正确传递question_id:

link_to'删除我的回答',answer_path(a,:question_id => @ question.id),:confirm => “你确定吗?”,:method => :删除

link_to的第二个参数是有问题的网址。您可以检查生成的HTML以确认数据正在按预期呈现。

这里还有其他一些选择:

根据您的路线和关系的设置方式,您可以将Answer设置为置于Question上下文中的嵌套路线。哪个会给你一组question_answer_path助手。

如果答案属于问题,你实际上只需在销毁行动中使用answer.question_id并省去麻烦:P