Develop a Rails object using AJAX and JavaScript

Within a music application built on Rails, I am attempting to monitor plays for tracks by artists. This involves creating a unique play object each time a visitor plays a track on the site. These play objects are assigned their own distinct IDs and are associated with specific tracks.

The functionality for creating these play instances is currently set up in the plays_controller.rb file within the API. However, I am encountering challenges in connecting this setup to the play buttons displayed on the page to ensure that playing a track triggers the creation of a new play object linked to that particular track.

Users have the ability to play tracks utilizing buttons structured like the following:

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

Displayed below are relevant segments from the routes.rb file to pinpoint the location of the plays_controller.rb in the API:

namespace :api, defaults: {format: 'json'} do
  namespace :v1 do
    resources :plays, only: [:index, :create]
  end
end

The snippet featured here illustrates key elements from 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

In addition, we highlight essential portions from 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 am struggling with implementing AJAX properly to generate a fresh play object. As an attempt, I integrated the following code into the `playTrack` function within the JavaScript mentioned above:

$.ajax({
  type: "POST",
  url: '/api/v1/plays',
  data: { track_id: trackId }
})

Regrettably, this method did not yield the desired outcome and resulted in an error message stating "param not found: play" (seemingly originating from the `play_params` in the `plays_controller.rb` Create action).

I would greatly appreciate any guidance or assistance in resolving this issue and ensuring its successful implementation.

Answer №1

When working with Rails, it is important to have nested params. For example, if you want to pass the track_id within a play object, the parameter should be named play[track_id]. One way to achieve this is by including a play object in your AJAX data, as shown below:

$.ajax({
  type: "POST",
  url: '/api/v1/plays',
  data: { play: { track_id: trackId } }
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The desktop display is experiencing a technical issue where menus are failing to appear

When my website is opened on desktop, the state remains false which causes no menus to show. I only want this functionality to be active on mobile devices. const Navbar = () => { const [isMenuOpen, setIsMenuOpen] = useState(false); const toggle = () ...

What are some ways to capture and save the window width prior to launching my Nuxt application?

I am working on a Nuxt application where I need to display different components based on the window width and send a request to create a session with the device width as one of the header parameters. Here is my approach: In my store code: //index.js expor ...

Angular - Detecting Scroll Events on Page Scrolling Only

I am currently working on implementing a "show more" feature and need to monitor the scroll event for this purpose. The code I am using is: window.addEventListener('scroll', this.scroll, true); Here is the scroll function: scroll = (event: any) ...

Adding information to a single class that shares a common name

Currently, I have successfully implemented a row cloning scenario where multiple dynamic rows are created after confirming an inventory number from a MySQL database. However, I am facing an issue with inserting the inventory data only to the next DIV eleme ...

Troubles with creating promises in Node.js

Currently, I am facing a challenge in Nodejs where I need to execute asynchronous tasks. Specifically, I need to navigate through all levels of a JSON object sequentially but synchronously. I am experimenting with the following code snippet, which is a si ...

What is the best way to showcase just 5 photos while also incorporating a "load more" function with

Is there a way to display only 5 images from a list on the first load, and then show all images when the user clicks on "load more"? Here is the code I have: $('.photos-list').hide(); $('.photos-list').slice(1, 5).show(); $ ...

Wait for the jQuery when function to finish processing AJAX requests

When utilizing this code inside an asynchronous function, the expected outcome is not achieved: Incorporating both the requests below: var result = await $.when( $.get('/api/1'), $.get('/api/2') ); Upon making just a single req ...

Pass information from Vue JS v-for to a button when it is clicked

Just started learning Vue JS and encountered a small issue I'm currently looping through an array with a button inside the div I'm iterating over The goal is to grab the data of the selected item after clicking on the button For example, suppo ...

Element sticking and bouncing

I'm currently facing an issue with Sticky-kit where one of my elements jumps when it reaches the bottom of its parent div. Below is the code snippet: <div class="wrapper"> <div id="bg"> <div id="text"> Lorem ipsum dolor sit a ...

Comparison between Filament Group's loadCSS and AJAX technologies

The loadCSS library developed by Filament Group is widely recognized as the standard for asynchronously loading CSS. Even Google recommends its use. However, instead of using this library, some suggest utilizing ajax to achieve the same result. For example ...

Remove click event listeners from a specific element within a group of selected elements using D3

In my D3 class, I have a group of selectors that I want to remove the click event from: d3.selectAll('.selectors').on('click',function(){ //Remove the click event from the currently clicked element. }); I'm encountering tw ...

Learn how to send back a modified view using ajax in asp.net mvc

I am encountering an issue with ajax. Here is the code. Model public class ViewModel { public long requestedVar { get; set; } public string ReturnedDescription { get; set; } } View Name: AddNewInfo <head> <script> $.datep ...

Updating cannot be done while rendering, within the onError function of the Image

I recently encountered a warning stating that I cannot update during render. The recommendation was to update in ComponentWillMount. However, since I need to change the state after checking if the image is in an Error (not Loaded) state, I must make the ...

Experiencing difficulties accessing the API route through Express

Every time I attempt to access /api/file, I am receiving a status code of 404. Here is the relevant code snippet: app.js : ... app.use("/api", require("./routes/users")); app.use("/api", require("./routes/file")); ...

JavaScript comparing elements within an array

I need help extracting all the names from an array with URLs containing '/blekinge' and presenting them in a list. Here's what I have so far: const allLocations = locations.map((location) => <li>{location.url}</li> ) I&a ...

Is it possible to guarantee that the initial AJAX request finishes before the next request is made?

I am working on a project that involves making consecutive async ajax calls to populate user schedules in an HTML table using jQuery. Each response returns a JSON serialized DataSet containing information about scheduled events and user details. The issue ...

Tips for managing onClick code when a user selects "open link in new tab" within a React js environment

How can I ensure that my tracking code runs when a user clicks a button in my React project, even if they open it in a new tab? Is there a solution for this in React JS? Here's a simple example: var Hello = React.createClass({ render: function( ...

Disabling the default behavior using preventDefault does not have an effect on ajax requests

I'm having an issue with my preventDefault event not working and I can't figure out why. I've searched around but haven't been able to pinpoint the problem. If there's a solution out there, please forgive me! Here's the code I ...

passing arguments during deferred resolve() and when() operations

I am currently working on a flash card website and I need to determine the status of preloaded images once they have finished loading or if there was an error. After obtaining the status of each image, I will proceed with further actions. My code is inspi ...

Enable automatic playback of HTML5 video with the sound on

I want to add an autoplay video with sound on my website, but I'm running into issues with newer browsers like Chrome, Mozilla, and Safari blocking autoplay if the video doesn't have a 'muted' attribute. Is there a clever HTML or Javas ...