I'm a beginner in Rails and I'm attempting to store a javascript variable from the view to the Rails Controller, which is then saved to a Model (database). The user participates in a quiz or survey and is then redirected to a results page. On this results page, there is JavaScript code that calculates the marks/results, and my goal is to save these marks to a database.
After some research, I found that the most effective solution is to utilize AJAX on the front-end to send the data to the controller on the back-end for processing.
I have a single controller named 'quiz' where I've implemented all the necessary methods, and a corresponding model called 'Score' to store the results. The user's result should be saved once they reach the result page.
This is what I have done so far:
In quiz_controller.rb
def result
@title = "Quiz Results"
end
def score
@mark = Score.all
end
def mark
quiz_name = params[:quiz]
mark = params[:mark]
@mark = Score.new(score_params)
@mark.save
end
private
def score_params
params.require(:score).permit(:quiz, :score)
end
In result.html.erb
<script>
var mark = calcMark();
$.ajax({
url: "http://localhost:3000/mark?quiz=" + quiz + "&mark=" + mark,
type: "POST",
success: function (data) {
console.log(data);
}
});
</script>
In 2019******_create_scores.rb
t.string "quiz", :limit => 50, :null => false
t.column "score", :decimal, :limit => 30, :null => false
t.datetime "created_at"
t.datetime "updated_at"
In routes.rb
get 'result' => 'quizs#result'
post 'result/mark' => 'quizs#mark'
If you have any suggestions on how to improve my implementation or if you notice any issues with my route configuration or AJAX URL, please let me know. Thank you in advance!