Concerning Rails 4 and Vanilla JavaScript, I encountered an issue with my code for creating a Shop record via Ajax. The record is successfully created, but the create.js
file is not being triggered as expected.
A strange occurrence happens in Chrome where it displays Rendered shops/create.js.erb
without any action taken, while Firefox shows ActionView::MissingTemplate
.
It appears that the request is being processed as HTML, which might be causing the problem.
# updated shops_controller.rb
class ShopsController < ApplicationController
def create
@day_id = params[:day_id]
shop_details = JSON.parse(shop_params[:shop]).with_indifferent_access
@shop = Shop.find_or_create_by(source_id: shop_details[:shop_id])
@shop.save
end
private
def shop_params
params.permit(
:shop,
:day_id
)
end
end
# revised global.js
function addShop(dayId, shop) {
var shopJSON = encodeURIComponent(JSON.stringify(shop));
var xhr = new XMLHttpRequest();
xhr.open("POST", "/shops", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.setRequestHeader("X-CSRF-Token", CSRF.token());
xhr.send("shop=" + shopJSON + "&day_id=" + dayId);
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE ) {
if (xhr.status != 200) {
alert('not ok');
}
}
};
}
# app/views/shops/create.js.erb
alert('good');
# Updated logs for Firefox:
Started POST "/shops" for 127.0.0.1 at 2017-01-08 13:11:36 +0800
Processing by shopsController#create as HTML
Parameters: {"shop"=>"...", "day_id"=>"85"}
Shop Load (0.4ms) SELECT `shops`.* FROM `shops` WHERE `shops`.`source_id` = 'ChIJHbeh32U6K4cR-lP5hY96smc' LIMIT 1
(0.2ms) BEGIN
SQL (3.6ms) INSERT INTO `shops` (`source_id`, `created_at`, `updated_at`) VALUES ('...', '2017-01-08 05:11:36', '2017-01-08 05:11:36')
(0.8ms) COMMIT
(0.2ms) BEGIN
(0.2ms) COMMIT
Completed 500 Internal Server Error in 34ms (ActiveRecord: 8.1ms)
ActionView::MissingTemplate (Missing template shops/create, application/create with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in:
* "/Users/abc/Sites/powerapp/app/views"
* "/Users/abc/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/devise-4.2.0/app/views"
):
actionview (4.2.6) lib/action_view/path_set.rb:46:in `find'
# Revised Chrome Log:
Started POST "/shops" for 127.0.0.1 at 2017-01-08 13:13:08 +0800
Processing by shopsController#create as */*
Parameters: {"shop"=>"...", "day_id"=>"79"}
Shop Load (0.3ms) SELECT `shops`.* FROM `shops` WHERE `shops`.`source_id` = 'ChIJASFVO5VoAIkRGJbQtRWxD7w' LIMIT 1
(0.2ms) BEGIN
SQL (9.2ms) INSERT INTO `shops` (`source_id`, `created_at`, `updated_at`) VALUES ('...', '2017-01-08 05:13:08', '2017-01-08 05:13:08')
(0.6ms) COMMIT
(0.2ms) BEGIN
(0.2ms) COMMIT
Rendered shops/create.js.erb (0.8ms)
Completed 200 OK in 44ms (Views: 25.1ms | ActiveRecord: 10.7ms)