Search code examples
ruby-on-railsruby-on-rails-5

Multiple Ajax links on a single page in Rails 5


I have the following code:

view

<% @jobs.each do |job| %>
      <tr>
        <td>
          <div class="job"><%= link_to(job.title, job.url, :target => "_blank") %>
          <a id="add-to-favorites"><i class="fa fa-heart" title="Save to my jobs"></i></a></div>
...

controller

  def add_to_favorites
    //I would like to see some params here also
    puts "made it to add_to_favorites"
  end 

JS

$("#add-to-favorites").click(function(){
        $.ajax({url: "add_to_favorites",
                        type: "GET",
                        data: {}
                    });
    });

route

  get 'add_to_favorites', to: 'jobs#add_to_favorites'

Two questions. First, how can I get the click/ajax call for each of the jobs. Right now it only works for the first job on the page. I am guessing this is due to my using id="add-to-favorites" for each of the jobs in the view. Should this be a unique id for each job?

Second, how do I pass params to the controller?


Solution

  • Your concern about the ids is correct. You should probably include an object id with the id attribute on your element. You can do something like:

    <%= link_to '#', id: "add-to-favorites-#{job.id}" do %>
      <i class="fa fa-heart" title="Save to my jobs"></i>
    <% end %>
    

    ...but that'll make it difficult to target via JavaScript. You might be better off doing something like this:

    <%= link_to '#', id: "add-to-favorites-#{job.id}", class: 'some-class', data: {id: job.id} do %>
      <i class="fa fa-heart" title="Save to my jobs"></i>
    <% end %>
    

    That way you can use the data-id attribute to get the id that you need.

    $(".some-class").click(function(e){
      e.preventDefault();
      var idToGet = $(this).data('id');
      data = {
        id: idToGet,
        // whatever else you need to pass to your controller as params
      };
    
      $.ajax({
        url: "add_to_favorites",
        type: "GET",
        data: data
      });
    });
    

    Anything you pass as data should show up in your controller as params. Also these kinds of things are usually configured to use a POST request.