In a Rails music app, I'm trying to count plays for artists' tracks by creating a play object when a visitor to the site plays a track. Each play has its own unique ID and belongs to a track.
Currently, I have the create functionality set up in the plays_controller.rb file in the API. However, I'm having trouble hooking it up to the play buttons on the page so that playing a track actually creates a new play object which belongs to that particular track.
Users can play tracks in the app using buttons like this:
<% @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 %>
Here are the relevant parts of the routes.rb file to show where the plays_controller.rb is located in the API:
namespace :api, defaults: {format: 'json'} do
namespace :v1 do
resources :plays, only: [:index, :create]
end
end
Here are the relevant parts of the plays_controller.rb file:
def create
@play = Play.create!(play_params)
render(:json => {}, :status => :created)
end
private
def play_params
params.require(:play).permit(:track_id)
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();
var trackId = track.id;
};
I'm not sure how to use AJAX to properly create a new play object. I've tried adding this to the playTrack function in the Javascript above:
$.ajax({
type: "POST",
url: '/api/v1/plays',
data: { track_id: trackId }
})
But it didn't work and gave me the error message "param not found: play" (which seemed to be thrown from the play_params in the plays_controller.rb Create action).
Any help getting this working would be much appreciated.
play_params?play_paramsin the third code snippet, the one fromplays_controller.rb