Filipe Gorges Reuwsaat Filipe Gorges Reuwsaat - 6 months ago 14
Ajax Question

What is the right way to deal with AJAX on Rails 4?

On most tutorials out there, people tell you to create a

template for every action you want to respond with
, which leads to having both an
and a
, for every action I want to work with AJAX, like this:

enter image description here

Is this right? Am I doing something wrong? Because it looks awful to me, there will be at least 20 files in each view folder, by default.


Yeah, it looks really awful to me too. But if you're responding to every method with javascript you'll have to create js.erb templates for each them.

Another approach would be, you'd want to respond with json instead of script. Where all your ajax code will remain in the client side javascript, and you'll be responded back with json data.

For eg. lets get data for an particular area

  url: "/areas/23",
  dataType: 'json',
  method: 'get',
  success: function(response){
    //OPTION 1
    //response will have all the data
    //handle the value from the response object in displaying

    //OPTION 2
    //If you set dataType: 'html' you can receive html partial from server and make use of it directly
    $("#show-area").html(response); //response will have content of _show.html.erb
  error: function(error){
    console.log(error); //Print errors if it breaks

def show
  respond_to do |format|
    #OPTIONS 1
    format.json { render json: @area.as_json } 
    #Or have a json.jbuilder partial if you want to send data selectively, ;) There is no escape from partials/templates

    #OPTION 2
    format.html { render partial: "areas/show" } # will render _show.html.erb


That being said, I think it finally comes to personal preference. And your preferences will vary upon different scenarios. You can pick any one of those based on the case. Let me know if it helped.