Andrew
Andrew

Reputation: 472

Increment Rails model column with Ajax/Javascript

I'm having trouble incrementing an integer column (plays) for the tracks model in a Rails music app. Users can play tracks in the app using buttons like this one:

<% @top_tracks.each do |track| %>
  <button class="track-play track-<%= track.id %>-play" onclick="playTrack(<%= track.to_json %>)">
    <i class="icon-play"></i>
  </button>
  ...
  [info about the track, such as <%= track.title %>]
  ...
<% end %>

And here are the relevant parts of the corresponding Javascript:

var player = document.getElementById('audio');

window.playTrack = function (track) {
    player.setAttribute('src', track.file_url);
    player.play();
};

I have read through answers to somewhat similar questions, such as this one, that suggest utilizing Ajax/Javascript, but I'm not sure how to do that to get the desired result in my case. I don't even know if Ajax/Javascript is the best way to achieve what I'm looking for.

What should happen is that every time a track is played and the playTrack() function is called, the value of the plays column for that track should be incremented by 1 and then (obviously) the new value for plays should be saved in the database.

Upvotes: 1

Views: 340

Answers (1)

Emu
Emu

Reputation: 5905

In your every track button add a data attribute say, data-track

<% @top_tracks.each do |track| %>
  <button data-track="#{track.id}" class="track-play track-<%= track.id %>-play" onclick="playTrack(<%= track.to_json %>)">
    <i class="icon-play"></i>
  </button>

<% end %>

in your routes.rb lets say declare:

post '/update_track_info', as: 'update_track_info', to: 'tracks#update_track_info'

create an ajax request:

window.playTrack = function (track) {
    player.setAttribute('src', track.file_url);
    player.play();
    $.ajax({
      url: '/update_track_info',
      data: { track_id: $(this).data('track').val() },
      type: 'POST'
    }) 

};

Then on the controller action:

def update_track_info
 @track = Track.find(params[:track_id].to_i)
 @track.update_column(:plays, @track.plays.next)    
 render :nothing => true
end

Upvotes: 1

Related Questions