【问题标题】:Rails helper method is called when I do not want to当我不想调用 Rails 辅助方法时
【发布时间】:2017-03-22 16:52:19
【问题描述】:

我正在尝试使用 Ruby on Rails 和 JavaScript 构建一个 4 选题测验应用程序。 如果您单击问题视图中的选择按钮之一,辅助方法“updateData(bool)”会更新数据库,然后您将看到没有视图转换的结果。如果您在回答后单击图表按钮,视图将转换为图表视图。

但是,辅助方法“updateData”似乎不仅由选择按钮调用,而且由图表按钮调用。它会根据我的期望更新数据库并增加问题编号。 根据console.log的输出,图表按钮调用JavaScript函数sendAnswer(ans)的可能性不大。

我使用 Rails 5.0.1。 我会很感激任何建议。谢谢!

<head>
  <script>
    function sendAnswer(ans){
      var questionID = getNumber();
      var data = readCSV(questionID);
      // True if answer number matches correct answer number
      if(data[5] == ans ){
        console.log("true")
        <% updateData(1) %>
      }else{
        console.log("false")
        <% updateData(0) %>
      };
      // Create Chart Button after answering
      $("#bottom").append('<div id="showChart"></div>');
      $("#showChart").html('<button id="showChartBtn" onclick="showChart()">Show Chart</button>');
    };
  </script>

  <script>
    function showChart(){
      window.location.href = "/chart";
    };
  </script>
</head>

<body>
  <% alphabets = ["A", "B", "C", "D"] %>
  <!-- For loop to make A-D choices -->
  <% for i in 0..3 %>
    <button class="choice_btn" id="btn_<%= i %>" onclick="sendAnswer(<%= i %>);">
      <%= alphabets[i] %>
    </button>
  <% end %>
 <div id="bottom">
  <!-- Chart Button comes here -->
  </div>
</body>
# Return user according to remember token
def current_user
  if (user_id = session[:user_id])
    @current_user ||= User.find_by(id: user_id)
  elsif (user_id = cookies.signed[:user_id])
    user = User.find_by(id: user_id)
    if user && user.authenticated?(:remember, cookies[:remember_token])
      log_in user
      @current_user = user
    end
  end
end

# Increment the Question Number, and increment the Correct Answer Number if true
def updateData(bool)
  current_user.questionNum += 1
  current_user.correctNum += bool
  current_user.save
end

【问题讨论】:

    标签: javascript ruby-on-rails ruby-on-rails-5


    【解决方案1】:

    在上面的 html 代码中,嵌入的 Ruby 在生成 HTML 时执行。

    我应该改为通过Button Click Event调用Controller Action,然后通过Action调用helper方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-27
      • 2012-12-30
      • 2016-07-22
      • 1970-01-01
      • 2012-02-13
      • 1970-01-01
      • 2012-08-19
      • 1970-01-01
      相关资源
      最近更新 更多