What is causing the internal server error in my Rails AJAX request?

I have a table with links on each line

 <%= link_to 'Delete', [lesson.group, lesson], remote: true, method: :delete%>

The goal is to delete the corresponding database entry and remove the line from the table without refreshing the page. The destroy action is defined as:

def destroy
        @lesson = @group.lessons.find(params[:id])

        @lesson.destroy

        respond_to do |format|
            if @lesson
                format.html { redirect_to edit_group_path(@group), notice:'Lesson successfully deleted' }
                format.js {}
            else
                format.html { redirect_to edit_group_path(@group), notice:'Error!' }
            end
        end
    end

Even though the entries are being removed, the changes are not visible until the page is reloaded, and the console shows:

DELETE http://localhost:3000/groups/1/lessons/14 500 (Internal Server Error) 

Log excerpt:

Started DELETE "/groups/1/lessons/18" for 127.0.0.1 at 2013-10-24 18:39:22 +0400
Processing by LessonsController#destroy as JS
  Parameters: {"group_id"=>"1", "id"=>"18"}
  [1m[36mGroup Load (1.0ms)[0m  [1mSELECT "groups".* FROM "groups" WHERE "groups"."id" = ? LIMIT 1[0m  [["id", "1"]]
  [1m[35mLesson Load (1.0ms)[0m  SELECT "lessons".* FROM "lessons" WHERE "lessons"."group_id" = 1 AND "lessons"."id" = ? LIMIT 1  [["id", "18"]]
  [1m[36m (0.0ms)[0m  [1mbegin transaction[0m
  [1m[35mSQL (4.0ms)[0m  DELETE FROM "lessons" WHERE "lessons"."id" = ?  [["id", 18]]
  [1m[36m (10.0ms)[0m  [1mcommit transaction[0m
Completed 500 Internal Server Error in 35ms

ActionView::MissingTemplate (Missing template lessons/destroy, application/destroy with {:locale=>[:en], :formats=>[:js, :html], :handlers=>[:erb, :builder, :coffee]}. Searched in:
  * "C:/Sites/timetable/app/views"
)

Answer №1

After destroying the object, it seems you are not handling what should happen next.

respond_to do |format|
        if @lesson
            format.html { redirect_to edit_group_path(@group), notice:'Lesson successfully deleted' }
            format.js {}
          # ...

The format.js {} part indicates that a response to JS is expected with either destroy.js.erb or destroy.html.erb, which appears to be missing based on the error message (

ActionView::MissingTemplate (Missing template application/destroy with {:locale=>[:en], :formats=>[:js, :html], :handlers=>[:erb, :builder, :coffee]}
).

You must either create the missing template, render another action where a template is defined using render action:, or consider doing a redirection (although it's uncertain if a simple redirect_to will work here). The request needs to have a definite conclusion through rendering or redirection.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Pop-up form for file uploading with MVC and AJAX consistently returns 'NULL' value in a system

I've been utilizing the code provided in this tutorial to upload rows to a SQL Server table. A new requirement has emerged which involves storing files on the server for "Evidence" purposes. In the form, I have implemented the following code: @using ...

Create custom AngularJS directives for validation and store them in a variable

Through the use of AngularJS, I've developed a directive called "integer" that invalidates a form if anything other than integers are entered. Because I'm generating the page dynamically by fetching data from the database, it would be helpful to ...

Allowing domain access when using axios and express

I have a server.js file where I use Express and run it with node: const express = require("express"); const app = express(), DEFAULT_PORT = 5000 app.set("port", process.env.PORT || DEFAULT_PORT); app.get("/whatever", function (req, r ...

Utilizing BEM Class Names in React

How can I utilize the Post component in a way that assigns unique classes to new and old posts following BEM recommendations? Assign a unique className to every element Avoid cascading dependencies like (.posts-new post or .posts-old post) Each component ...

Is there a way to customize the color of the HR element in a Material-UI Select Field?

https://i.stack.imgur.com/DYeX7.png https://i.stack.imgur.com/CN0T6.png Hi there, I am currently working on a website and using a Select Field component from Material-UI. I am faced with the challenge of customizing the style to change the default light ...

What could be causing my JSON file not to display when the onclick event is triggered?

I am currently learning JavaScript and JSON, as I am enrolled in a class that focuses on these topics. Our latest project requires us to create a JSON file and use a button along with JavaScript to display its contents. I have spent countless hours trying ...

Trouble with the datepicker

I tried using the datepicker from and followed its demo, but unfortunately, the datepicker is not showing up on my page. I have gone through everything carefully, but I am unable to identify the reason behind this issue. Could someone please assist me i ...

When a directive is passed a string with HTML tags, the tags are not displayed/rendered as expected

When it comes to passing a string with HTML content to my Angular directive, I've encountered an issue where the rendered output treats the HTML as text. While researching possible solutions, most of them seem to rely on using ng-bind-html directive, ...

Webpack is having trouble resolving the specified file or directory

MyAPP: |--src   |--index.js   |--content.js |--webpack.config.js index.js : const React = require('react'); const ReactDom = require('react-dom'); const View = require('./content'); ReactDom.render(<View/ ...

Instead of showing the data in the variable "ionic", there is a display of "[object object]"

Here is the code snippet I'm working with: this.facebook.login(['email', 'public_profile']).then((response: FacebookLoginResponse) => { this.facebook.api('me?fields=id,name,email,first_name,picture.width(720).height( ...

JavaScript heap ran out of memory near heap limit during mark-compacts, rendering the allocation ineffective, resulting in a failed Ionic 3 production build

While attempting to build a production version of my Ionic 3 app, I encountered the following error: "FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory". To troubleshoot this issue, I duplicated the en ...

Determine the Total of Various Input Numbers Using JQuery

There are 3 input fields where users can enter numbers, and I want to calculate the sum of these numbers every time a user updates one of them. HTML <input class="my-input" type="number" name="" value="0" min="0"> <input class="my-input" type="n ...

Tips for effectively utilizing an if/else structure to animate fresh content from the right while smoothly removing old content by sliding it to the left

document.getElementById("button1").addEventListener("click", mouseOver1); function mouseOver1(){ document.getElementById("button1").style.color = "red"; } document.getElementById("button2").addEventListener("click", mouseOver); function mous ...

Combining a form and table on a single webpage, I am curious how to utilize the form to update the table effectively using Express and Node.js

Seeking guidance in website development as I face a particular challenge. I aim to create a dynamic search page for a website. The form should allow users to select a location or category, with the same page updating with relevant results. Despite succes ...

Understanding how to properly handle the data sent by an ajax request in a NodeJS server

I currently have an array called passedWord = ['a', 'bbb']. I am then making an AJAX request to send this array to a Node.js server. Upon receiving the array on the server, Body Parser returns the following object: { name: 'abc&ap ...

The "if" statement carries out the identical action each time it is executed

Despite my efforts to toggle the value of the turn variable every time the if statement runs, I keep encountering the same outcome. It appears that turn consistently evaluates as 2. Below is the code snippet in question: $(function() { var turn = 2; ...

jQuery AJAX Live Search Function Only Executes Once

Here is a code snippet for a live search functionality: <script> $(".search").keyup(function() { var Team_Name = $('#TeamName').val(); var Teacher = $('#Teacher').val(); var Searc ...

passing a variable from PHP to JavaScript

When I attempted to transfer variables from PHP to JavaScript, I found myself quite confused. It was straightforward for me to retrieve values using an ID, like this: var name = $("#name").val(); However, my question is if I want to convert a variable li ...

Sharing methods between controllers in AngularJS

After coming across this insightful article on Angular validation, I decided to implement it in my project. The validation is functioning perfectly, but I am struggling to access methods in other controllers upon successful form validation. Despite trying ...

Display a standard chart using the Chart.js library, along with customizable options

I have successfully generated charts from a database using JSON script. However, I am facing an issue where the chart only displays when I click on an option value. What I want to achieve now is setting a default value option so that when the website ope ...