banditKing
banditKing

Reputation: 9579

checkbox_tag in a HTML table in rails app - using AJAX to update model

I'd like to make the following checkboxes and radiobuttons invoke the "update" method in my listings_controller

How do I make that happen? I've coded the elements there within my table but how can I have them send the parameters? I would like to use AJAX where do I begin?

    <%= stylesheet_link_tag 'listings' %>
    <h1>Listing listings</h1>
    <table class="datatable">
    <tr id="heading" >
     <th >id</th>
     <th >name</th>
    </tr>

    <% @listings.each do |listing| %>
      <tr id="body">
    <th><%=listing.id%></th>
        <th><%= link_to listing.name, edit_listing_path(listing) %></th>

    #How can I have the following invoke the update method in AJAX format
     <td><%= radio_button_tag(:keep, "Keep") %>
        <%= label_tag(:keep, "Keep") %></td>
    <td><%= radio_button_tag(:keep, "Delete") %>
        <%= label_tag(:keep, "Delete") %></td>
    <td><%= check_box_tag(:checked) %>
        <%= label_tag(:checked, "checked") %></td>
    <td><%= check_box_tag(:collected) %>
        <%= label_tag(:collected, "collected") %></td>
    <td><%= check_box_tag(:digitized) %>
        <%= label_tag(:digitized, "digitized") %></td>
    <td><%= check_box_tag(:in_database) %>
        <%= label_tag(:in_database, "in database") %></td>
      </tr>
    <% end %>
</table>
<br />
<%= link_to 'New Listing', new_listing_path %>

Thanks a lot.

Upvotes: 0

Views: 597

Answers (1)

Jordan Scales
Jordan Scales

Reputation: 2717

You're needs are pretty vague, but definitely use jQuery for this. Go into app/assets/javascripts/listings.js.coffee and try the following.

$('input.some_class').bind('update', ->
  $.post('/listings/update', { param1: value, param2: value ... }, (data) ->
    alert('updated!')

Or just plain javascript (app/assets/javascripts/listings.js)

$('input.some_class').bind('update', function() {
  $.post('/listings/update', { param1: value, param2: value ... }, function(data) {
    alert('updated!');
  });
}); 
  • Give your checkboxes, radio buttons, etc some class name
  • Fill in the appropriate fields for the data you want to send (the data accepted by the updates method in your listings controller)
  • Put appropriate code for call back (rather than alert('updated!'), you could even put nothing at all)

But again, your needs are a little vague, I hope this is a good starting point. I'm going to recommend learning jQuery and maybe coffeescript before attempting to incorporate AJAX into your project. You could tweak it a little to utilize :remote => true as well, but that's another story.

Upvotes: 1

Related Questions