Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

290
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda