首页 > 解决方案 > Rails-在创建操作期间根据表单输入重定向到不同的路径

问题描述

我的控制器中有一个创建操作。

 def create

        @client=Client.find(params[:client_id])
        @comment= @client.build_comment( comment_params )
        if @comment.save

        flash[:success]= "Thank you!"
        redirect_to path_one
        else
            render action: :new
        end

    end
        private
        def comment_params
            params.require(:comment).permit(:response, :experience)
        end

现在在我的创建操作中,每当我的客户提交表单时,我希望能够根据“经验”的值重定向到不同的路径。

所以,如果体验是“积极的”,我希望他们去 path_one,如果体验是“消极的”,我希望他们去 path_two。

我试过这个:

def create

        @client=Client.find(params[:client_id])
        @comment= @client.build_comment( comment_params )
        if @comment.save
             if params[:experience]=="positive"

                  flash[:success]= "Thank you!"
                  redirect_to path_one
                  else
                  render action: :new
             else
             redirect_to path_two
        end
        end 
end
        private
        def comment_params
            params.require(:comment).permit(:response, :experience)
        end

但这总是重定向到相同的路径。

标签: ruby-on-rails

解决方案


您的 if 语句的else部分顺序错误。尝试这个:

if @comment.save
  if params[:experience]=="positive"
    flash[:success]= "Thank you!"
    redirect_to path_one
  else
    redirect_to path_two
  end
else
  render action: :new
end

推荐阅读