【问题标题】:Rails parameters contain backslashesRails 参数包含反斜杠
【发布时间】:2018-12-31 03:57:35
【问题描述】:

我目前正在与button_tag 合作创建一个远程样式的答案提交测验。按下此按钮时,不是发布新记录,而是抛出错误。

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

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

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

这是我正在使用的button_tag

<% @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 或其他论坛的其他地方找到任何解决方案。有任何想法吗?

【问题讨论】:

  • 你试过用button_to代替button_tag吗?第一种方法可以更好地控制远程,而无需使用data
  • 这很尴尬。我早些时候尝试过没有成功,但现在似乎已经奏效了。谢谢。
  • 成功不丢人!如果您有一个可行的解决方案,使用这种方法将修改后的代码显示为自我回答,这对其他人来说是有教育意义的。

标签: ruby-on-rails ruby


【解决方案1】:

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

button_tag 创建一个按钮元素,定义提交按钮、重置按钮或可在 JavaScript 中使用的通用按钮。 button_tag 也是一个动作视图助手,但被定义为一个 FormTagHelper。

button_to 生成一个包含单个按钮的表单,该按钮提交到由一组选项创建的 URL。 button_to 是 UrlHelper,而 button_tag 是 ViewHelper。

下面是我使用的button_tag 代码,它导致了上述问题。使用button_tag 修复了我的参数问题,而且看起来也更干净了。我希望这可以帮助其他任何人在未来遇到button_tag 的问题。

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

【讨论】:

    猜你喜欢
    • 2011-05-15
    • 2022-07-07
    • 1970-01-01
    • 1970-01-01
    • 2014-12-25
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多