Mina Almasry
Mina Almasry

Reputation: 173

serving javascript with rails

I have this code down here. When format.js fires I want to serve to the client a javascript file. How do I do that?

class LineItemsController < ApplicationController

def destroy
  @line_item = LineItem.find(params[:id])
  @line_item.destroy

  respond_to do |format|
    format.html { redirect_to line_items_url }
    format.js {}
    format.json { head :no_content }
  end
end

I have a file called destroy.js.erb in the controller, but that doesn't run automatically. I tried many combinations but nothing seems to work...

what do I put inside format.js { ??? } to serve a javascript file I want? I don't want to write vanilla javascript.

Upvotes: 0

Views: 414

Answers (1)

jdoe
jdoe

Reputation: 15771

To trigger your js-response of your destroy action try:

<%= button_to 'Remove', @line_item, method: :delete, remote: :true %>

For testing purpose make your destroy.js.erb as the following:

alert("Line item with id <%= @line_item.id %> has been removed");

You can leave your format.js w/o bracket (or with empty ones).

Upvotes: 2

Related Questions