views:

46

answers:

1

Hi all!

I have this rather simple Ruby on Rails application : two models Lists and Items. Lists have many Items and Items belong to Lists. OK.

The show method of ListsController prints a page with the list of the items belonging to the given list (in a partial lists/_listOfItems.html.erb). At the end of the show.html.erb view, there is a form that lets users add an item to the list. In standard (no jQuery) RoR, this works perfectly.

Now, what I want to do is let user add an item to the list without reloading the page. I have managed with jQuery to add the item to the database but now my problem is to refresh the html list without reloading the page. I have managed to have a create.js.erb executed in ItemsController and I can make things appear on the page with it but the problem is that this create.js.erb lives in ItemsController and not in ListsController so that if I try to make create.js.erb render the partial _listOfItems.html.erb, it will fail since create.js.erb lives in ItemsController and hence cannot access the variables defined in the show method of ListsController.

I guess it would work like a charm if I was using the index method of ItemsController to display the list of items since everything would be living in there but that might yield further complications.

I hope that was clear. Can you help me? Thank you very much!

A: 

If I understand right I think the solution lies in javascript + an action in your controller:

your show view should have an ajax call as follows, this should be triggered by a click/change/... jquery function, for example: $("selector").change(function() { here the ajax call is placed })

  $.ajax( {
    type: 'get',
    url: "/ajax/somepageofyourown",
    async: false,
    data: { add here any variables your controller method would need },
    success: function( r ) {
      $(' the selector that needs to be replaced ').html( r );
    }
  } );

add the url that this ajax calls to your routes, so that your controller responds

add your controller action, it should trigger that renders the html that you want to replace the previous html with.

PlanetMaster
Hi, Thank you for your reply. I guess I should have mentioned that I am using the jQuery form plugin which I believe is taking care of all the ajax calls. I'll try to figure out how to do it.
Manu