Correct way to make view updates in Rails

Viewed 61

So, I have a serious doubt for sometime. I see many people using ajax to make server requests when a update is needed in the front end. But what is the real difference between using ajax or for example using a link_to. For example I have this ajax code, which makes a server request to like a post:

$(function(){
    $(".pos-like").on("click", function(){
        var post_id = $(this).data("id")
        $.ajax({
            url: "/post/like/" + post_id,
            method: "POST"
        }).done(function(response){
            console.log(response)

        })
    })
});

But in another case, it also works if I use a link_to in the view for that same request.

<%= link_to like_path(post_id: post.id) do %>
     <i class="fa fa-heart fa-2x post-like"></i>
<% end %>

Then in the controller I just render a partial that just changes the color of the like button (using jquery).

My question is, why do people normally use Ajax to make updates, when they can just use, for example, a link_to in the view. Are there any benefits when using ajax?

Thanks!!

1 Answers

Remote elements in Rails' views are something that actually does Ajax calls behind the scenes. So the difference here is that:

  • The first example you are explicitly calling whatever you want to be called when something is clicked
  • The second example you are using Rails Ajax helpers to achieve the same goal, which will in fact call a block of JS that is very similar to the first example
Related