I am new to JavaScript and Jquery as a front-end for Rails, and I am having trouble getting my next button on my show page to load the next object. Can anyone take a look and see where I may be going wrong? Thanks in advance! Here is the relevant code:
show.html.erb
<%= render 'layouts/header' %>
<% if @car %>
<a href="#" class="js-next" data-id="<%=@car.id%>">Next Car</a>
<h1 class="carMake"><%= @car.make %></h1>
<h1 class="carModel"><%= @car.model %></h1>
<p class="carYear"><%= @car.year %></p>
<p class="carColor"><%= @car.color %></p>
<% end %>
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$(".js-next").click(function(event) {
event.preventDefault();
var nextId = parseInt($(".js-next").attr("data-id")) + 1;
$.get("/cars/" + nextId + ".json", function(data) {
$(".carMake").text(data["make"]);
$(".carModel").text(data["model"]);
$(".carYear").text(data["year"]);
$(".carColor").text(data["color"]);
// re-set the id to current on the link
$(".js-next").attr("data-id", data["id"]);
});
});
});
</script>
Show method in cars controller
def show
@car = Car.find(params[:id])
respond_to do |format|
format.html {render :show}
format.json {render json: @car}
end
end
car serializer
class CarSerializer < ActiveModel::Serializer
attributes :id, :make, :model, :color, :year
end
Terminal response when I click on next
Started GET "/cars/8" for 127.0.0.1 at 2018-03-09 12:17:24 -0700
Processing by CarsController#show as HTML
Parameters: {"id"=>"8"}
Car Load (0.2ms) SELECT "cars".* FROM "cars" WHERE "cars"."id" = ? LIMIT ? [["id", 8], ["LIMIT", 1]]
CACHE Car Load (0.0ms) SELECT "cars".* FROM "cars" WHERE "cars"."id" = ? LIMIT ? [["id", 8], ["LIMIT", 1]]
Rendering cars/show.html.erb within layouts/application
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]]
Rendered layouts/_header.html.erb (6.5ms)
Rendered cars/show.html.erb within layouts/application (13.7ms)
Completed 200 OK in 265ms (Views: 260.4ms | ActiveRecord: 0.7ms)
Please let me know if any other code snippets would be helpful in diagnosing the problem. Thanks!