Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

294
Views
Rails how to pass a variable with Fetch

How do you pass a variable with fetch in Rails? Here is the current workflow and why I'm trying to do that. This workflow is an intermediate step to creating a progress bar.

  1. Click a link in the view which calls a controller action (books#index).
  2. The controller then returns a js file.
  3. The js file then uses fetch to call another controller action (application#percentage_done) passing it the worker id.
  4. Application#percentage_done then uses the worker id to find the completion status of the worker and returns that data as a json.
  5. The js file then prints the contents of the json to the consol.

I can use the js code below to successfully call the application#percentage_done action. However, it doesn't pass the worker id. Code obtained from https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

fetch('/application/read_percentage_done')
  .then(response => response.json())
  .then(data => console.log(data));

This is my attempt at using fetch to pass the worker id. But it gets a 422 error. This code was adapted from Use fetch to pass variable in rails

async function postData(url = '', data = {}) {
  const response = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  });
  return response.json();
}

postData('/application/percentage_done', { data: '<%= @worker_id %>' })
  .then(res=> { console.log(res) });

Here is the contents of the config/routes.rb file.

Rails.application.routes.draw do
  require 'sidekiq/web'
  mount Sidekiq::Web => '/sidekiq'
  root "books#index"
  post "application/percentage_done" => "application#percentage_done"
  resources :books
end
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!