I am using Rails 6.1.4 and ruby 2.6.7
I have an app that tracks weight lifting exercises. On the new record form (view) I have a select box to pick an exercise to perform. What I would like to do is when the onChange event for the drop down is triggered, I would like to fetch the last record created for that exercise and display it as text above the form. I do not want the record to show in the form elements, just as text. I or users can use the last record to gauge their progress.
I've done this sort of programming many times in PHP using JQuery and ajax calls, but have never done it with rails. I do not know how an ajax call to a separate file (helper?) can send a value to the controller (new action?) and be seen on the new form without making a separate request to the form page.
My view:
apps/views/fitness/weights/new (_form)
<div class="grid-x">
<div class="cell medium-2">Exercise/Routine:</div>
<div class="cell medium-2"><%= f.select(:exercise, options_for_select(@exercises)) %></div>
</div>
The above becomes:
<select name="fitness_weight[exercise]" id="fitness_weight_exercise">
Are there any tutorials on this? I have not found any in my Googling. Any pointers would be appreciated.
Thanks
@Oliver Trampleasure - Thanks for pointing me in the right directions: I found a couple of web sites that explained how to make this type of thing work. Between them I came up with the following, which works just how I wanted.
views/fitness/weights/_form (partial)
<div id="target-for-change"></div>
fitness/weights_controller.rb#test (new action for this)
def test
# run sql to get last record with exercise like the one chosen in the weights new form.
if params[:exercise]
@exercise=Fitness::Weight.where(admin_user_id: session[:user_id]).where(exercise: params[:exercise]).last
else
# default exercise
@exercise=Fitness::Weight.where(admin_user_id: session[:user_id]).where(exercise: 'BENCH PRESS').last
end
# send vals back to application.js
return render json: {exercise: @exercise.exercise,
workout_date: @exercise.workout_date_formatted,
weight_set_1: @exercise.weight_set_1,
reps_set_1: @exercise.reps_set_1,
weight_set_2: @exercise.weight_set_2,
reps_set_2: @exercise.reps_set_2,
weight_set_3: @exercise.weight_set_3,
reps_set_3: @exercise.reps_set_3,}
end
application.js
$(document).ready( function(){
...
// user selects an exercise from drop-down on form
$('#fitness_weight_exercise').change(function(){
$.ajax({
url: "18/test", // 18 is just a number needed for the route. any nbr will do
dataType: "json",
data: {exercise: $(this).val()},
success: function(data){
$('#target-for-change').html("<p><b>Last " + data.workout_date + ":</b><br />"
+ " set 1: " + data.weight_set_1 + " x " + data.reps_set_1
+ " ---- set 2: " + data.weight_set_2 + " x " + data.reps_set_2
+ " ---- set 3: " + data.weight_set_3 + " x " + data.reps_set_3
+ "</p>");
}
});
});
...
});