Rails with Ajax

Hi all, looking into ajax support on rails but I can't seem to get
sometime simple to work.

I basically started off with a simple scaffold app, seeded the
database with some dummy data and trying to get delete working as a
ajax request.

rails g scaffold pony name:string profession:string

My delete like looks like this (added remote: true).

<%= link_to 'Destroy', pony, method: :delete, remote: true, class:
'delete_pony' %>

I created a new file: app/views/ponies/destroy.js.erb which I don't
see getting called as I added an alert alert box to check.

$('delete_pony').ajaxSuccess( function() {

My controller method looks like this

  def destroy
    respond_to do |format|
      format.html { redirect_to ponies_url, notice: 'Pony was
successfully destroyed.' }
      format.json { head :no_content }
      format.js { render layout: false }

What am I missing?


If you take a look at your server’s console you will see the error. From what I see, the second argument of the link helper expects a url but you pass an object (I suppose this variable exists otherwise the view with the link wouldn’t render).

This should work:

<%= link_to ‘Destroy’, pony_path(pony), method: :delete, remote: true, class: ‘delete_pony’ %>



OK I just noticed inside my jquery I was missing the dot '.' before
the class name!

Hi Lazaruz,

in the link_to call, when you only provide a variable, by rails
conventions the object's id value will be used and the show method
will be called.

fyi there were actually two correction I had to make in the javascript
code, in addition to what I mentioned earlier, I also has to change
jQuery method "ajaxSuccess" to use the "on" method like this.

$('.delete_pony').on( 'ajax:success', function() {