Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

293
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda