1

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.

2
  • what's in play_params ? Commented Sep 7, 2015 at 6:16
  • @Nithin, I showed the play_params in the third code snippet, the one from plays_controller.rb Commented Sep 7, 2015 at 6:18

1 Answer 1

2

Rails expects the params to be nested, e.g. play's track_id should be named play[track_id]. You can probably solve this by including a play object in your AJAX data, like this:

$.ajax({
  type: "POST",
  url: '/api/v1/plays',
  data: { play: { track_id: trackId } }
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.