Rails (5.2.2) AJAX call for partial not working

Viewed 963

Short and sweet, I have followed this guide exactly on a fresh rails deployment (5.2.2), using rails g scaffold thing to generate the app.

However, after making the partial _show.html.erb under the paragraph Targeted Changes in the guide, clicking the "Change below" link_to does not render the partial when testing. I get no error message, and Rails tells me that everything is rendered OK, but nothing happens on the site when I click the link.

What am I missing?


Code:

controllers/things_controller

class ThingsController < ApplicationController

  def index
    @things = Thing.all
  end

  def show
  end

end

config/routes.rb

Rails.application.routes.draw do
  root 'things#index'
  resources :things
end

things/index.html.erb

<%# /app/views/things/index.html.erb %>
<%= link_to 'Change Below', thing_path(42), remote: true %>

<div id="target-for-change">
  Now you see "ME"!
</div>

things/show.js.erb

<%# /app/views/things/show.js.erb %>
$("#target-for-change").html("<%= j render(partial: 'show') %>");

things/_show.html.erb

<%# /app/views/things/_show.html.erb %>
Now you don't!

Browser Console output:

Uncaught ReferenceError: $ is not defined
    at <anonymous>:1:1
    at processResponse (rails-ujs.self-d109d8c5c0194c8ad60b8838b2661c5596b5c955987f7cd4045eb2fb90ca5343.js?body=1:268)
    at rails-ujs.self-d109d8c5c0194c8ad60b8838b2661c5596b5c955987f7cd4045eb2fb90ca5343.js?body=1:196
    at XMLHttpRequest.xhr.onreadystatechange (rails-ujs.self-d109d8c5c0194c8ad60b8838b2661c5596b5c955987f7cd4045eb2fb90ca5343.js?body=1:251)
2 Answers

You need to add the jquery in your project. Add this line to application.html.erb

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

Or you can use the gem jquery-rails

As you can see on your console output, '$' is not defined. '$' is the common alias for jQuery so when you do:

$("#target-for-change").html("<%= j render(partial: 'show') %>");

you are telling jQuery to find a certain identifier. The thing is that you did not include the library in your project. A way to do it is by adding this line in your gemfile:

gem 'jquery-rails'

and then this in your assets/javascripts/application.js

//= require jquery3
Related