2017-03-22 6 views
-2

Ruby on RailsとJavaScriptを使用して4つの選択肢のクイズアプリケーションを構築しようとしています。 質問ビューで選択ボタンの1つをクリックすると、ヘルパーメソッド "updateData(bool)"によってデータベースが更新され、ビュー遷移なしの結果が表示されます。また、応答後にグラフボタンをクリックすると、グラフビューに遷移します。私はしたくないときにRailsヘルパーメソッドが呼び出される

しかし、ヘルパーメソッド "updateData"は、Choice ButtonではなくChart Buttonによって呼び出されるようです。それはデータベースを更新し、私の期待に反して質問番号を増やします。 console.logの出力によると、Chart ButtonがJavaScript関数sendAnswer(ans)を呼び出す可能性は低いです。

私はRails 5.0.1を使用します。 私は何かアドバイスをいただきありがとうございます。ありがとう!上記のHTMLコード内

<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 

答えて

0

、HTMLを生成しながらルビー<%にupdateData%>が実行される埋め込み。

代わりに、ボタンクリックイベントでコントローラアクションを呼び出す必要があります。次に、アクション経由でヘルパーメソッドを呼び出します。

関連する問題