简体   繁体   中英

Why does my rails AJAX request throw internal server error?

I have a table , where each line has a link

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

I want the link to destroy the corresponding db entry and remove the corresponding line from the table without reloading the page. The action is

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:'Succesfully deleted lesson' }
                format.js {}
            else
                format.html { redirect_to edit_group_path(@group), notice:'Error!' }
            end
        end
    end

The entries get removed, but I can only see the change when I reload the page, and the console throws

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

Extract from the log:

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"
)

Because you're not handling what should happen after you destroy that object.

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

The format.js {} here says "resond to JS with destroy.js.erb or destroy.html.erb or similiar", which you don't have set up, according to your error ( ActionView::MissingTemplate (Missing template application/destroy with {:locale=>[:en], :formats=>[:js, :html], :handlers=>[:erb, :builder, :coffee]} ).

You either need to set up that template, or render another action (with eg render action: ) where a template is defined. Or you could do a redirect (which I am not sure if a simple redirect_to works here). But the request needs to "end" somehow, either by rendering or redirecting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM