代码之家  ›  专栏  ›  技术社区  ›  Trenton Tyler

Rails参数包含反斜杠

  •  1
  • Trenton Tyler  · 技术社区  · 6 年前

    我目前正在与 button_tag 创建一个远程风格的答案提交测验。按下此按钮而不是发布新记录时,会引发错误。

    ActiveRecord::RecordNotFound (Couldn't find Answer without an ID):

    当查看服务器日志时,我发现它在尝试发布时试图使用这些参数。 Parameters: {"{\"answer_id\":59}"=>nil, "id"=>"15"}

    我在看,或者期待看到的就是这个。 Parameters: {"answer_id"=>"59", "id"=>"15"}

    这里是 钮扣标签 我在用。

    <% @question.answers.each do |answer| %>
      <%= button_tag "#{answer.answer.titleize}", class: 'btn btn-block btn-lg btn-primary', data: {
        remote: true,
        method: :post,
        url:    answer_question_path(@question),
        params: { answer_id: answer.id }
      } %>
    <% end %>
    

    这是我的响应控制器,负责提交POST请求。

    class ResponsesController < ApplicationController
        def answer
            question = Question.find(params[:id])
            answer   = question.answers.find(params[:answer_id])
            response = question.responses.find_or_initialize_by(user: current_user)
    
            if response.update(answer: answer)
                head :ok
            else
                puts 'Something went wrong chief' 
            end
        end
    
        private
    
        def responses_params
            params.require(:response).permit(:user_id, :question_id, :answer_id)
        end
    end
    

    我试过用 to_json 在参数上没有成功,并且在SO或其他论坛上找不到任何解决方案。有什么想法吗?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Trenton Tyler    6 年前

    这似乎是一个问题 button_tag 在我使用它的功能中。

    钮扣标签 创建一个button元素,该元素定义一个submit按钮、resetbutton或一个可在javascript中使用的通用按钮。 钮扣标签 也是操作视图助手,但定义为FormTagHelper。

    button_to 生成一个表单,其中包含一个提交到由选项集创建的URL的按钮。 纽扣 是个冲浪运动员 钮扣标签 是一个ViewHelper。

    下面是 钮扣标签 我使用的代码创建了上面描述的问题。使用 钮扣标签 修正了我的参数问题,看起来也比较干净。我希望这能帮助任何有问题的人 钮扣标签 未来。

    <%= button_tag "#{answer.answer.titleize}", class: 'btn btn-block btn-lg btn-primary', data: {
        remote: true,
        method: :post,
        url:    answer_question_path(@question),
        params: { answer_id: answer.id }
      } %>
    
    
    <%= button_to "#{answer.answer.titleize}", 
          answer_question_path(@question), 
          class: 'btn btn-block btn-lg btn-primary',
          params: { answer_id: answer.id },
          remote: true %>