Create record on click with ajax

I have a list of elements, which should create or delete a record in a table when clicked. Each element has some data attributes associated with it to create/destroy the correct record. I am wondering the correct 'rails' way to accomplish this?

Element list:

<div>
    <h3 data-date="2016-06-11 09:00:00 UTC" data-swimmer-id="1">Lisa</h3>
    <h3 data-date="2016-06-11 09:00:00 UTC" data-swimmer-id="2">Karen</h3>
    <h3 data-date="2016-06-11 09:00:00 UTC" data-swimmer-id="3">Susan</h3>
    <h3 data-date="2016-06-11 09:00:00 UTC" data-swimmer-id="4">Liz</h3>
</div>

Upvotes: 0

Views: 211

Answers (1)

Emu
Emu

Reputation: 5905

You can use ajax-rendering.

Let's say there is a controller named SwimmerController, it should create/delete your data from a model.

class SwimmerController
   respond_to :js
   def create
      # create something
      render :layout => false # you can turn that off and can render a partial
   end

   def destroy
      # destroy something
      render :layout => false 
   end
end

Now, in the view, Add a :remote => true flag to the triggering element

<div>
    <a href="<%= create_path_of_swimmer_controller %>" data-remote="true" method="post"><h3 data-date="2016-06-11 09:00:00 UTC" data-swimmer-id="1">Lisa</h3></a>
    <h3 data-date="2016-06-11 09:00:00 UTC" data-swimmer-id="2">Karen</h3>
    <h3 data-date="2016-06-11 09:00:00 UTC" data-swimmer-id="3">Susan</h3>
    <h3 data-date="2016-06-11 09:00:00 UTC" data-swimmer-id="4">Liz</h3>
</div>

For better understanding see this post

Upvotes: 1

Related Questions