I've been scouring the internet for information on this topic, but I'm having trouble understanding how AJAX works with Rails. I've gone through the documentation multiple times and it's just not clicking for me.
From what I gather, AJAX is asynchronous and all you need to do to make a request in the view is add the code "remote: true
". However, the part that's tripping me up is this line of code:
respond_to :js
It seems like it instructs the controller to respond to Javascript and you have to create a file for whatever JS action you want to perform. My project structure looks like this:
View
New.html.erb:
<p>Image Upload</p>
<%= simple_form_for @entries, remote: true do |f| %>
<% f.file_field 'input-image' %>
<% end %>
<div id="image-entry"></div>
View route:
views
|
-->admins
|
-->entries
|-->new.html.erb
|-->new.js.erb
Controller
entries_controller.rb
module Admins
class EntriesController < ApplicationController
before_action :authenticate_admin!
def index
render 'index'
end
def new
@entries=''
render 'new'
respond_to :js
end
end
end
Controller route:
controllers
|
-->admins
|
-->entries_controller.erb
JS
new.js.erb
console.log('it works');
$('#input-image').click(function(){
$('body').css('background-color', 'red');
});
JS route:
views
|
-->admins
|
-->entries
|-->new.html.erb
|-->new.js.erb
Error
The error message I encounter is as follows:
ActionController::UnknownFormat
So, I have some questions about this error and also regarding the correct naming convention for the JS file to ensure that respond_to
functions correctly.