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

213
Visualizações
How do I pass an object in the rails URL helper

I'm having an issue understanding how to setup the routes in rails to pass an object into the URL helper.

I added a new method add_item

  def add_item
    @item = Item.create(item_params)
    puts @hospital.inspect
    puts @item.inspect
    @hospital.items << @item

    respond_to do |format|
      if @hospital.save
        format.html { redirect_to hospital_url(@hospital), notice: "Item was added to hospital" }
        format.json { render :show, status: :ok, location: @hospital }
      else
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @hospital.errors, status: :unprocessable_entity }
      end
    end
  end

I added the corresponding route

  resources :hospitals do
    member do
      post :add_item
    end
  end

but when I run my test that uses

      post add_item_hospital_url(@hospital), params: { item: { item_code: item.item_code, description: item.description, gross_charge: item.gross_charge } }

the @hospital in the test is not nil but on the controller, it is. What am I doing wrong? My routes seem to be okay.

add_item_hospital POST   /hospitals/:id/add_item(.:format)
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The instance variable @hospital is nil in the controller because it has not been set. Maybe you could add a before_action to set the value of the instance variable or just add it to the add_item method.

When passing models into the URL helper the id of that object can be found within the params hash

class HospitalsController < ApplicationController
  before_action :set_hospital, only: :add_item
  
  def add_item
    # ... your code here
  end

  private
    def set_hospital
      @hospital = Hospital.find(params[:id])
    rescue ActiveRecord::RecordNotFound
      # handle exception
    end
end
over 4 years ago · Santiago Trujillo Relatório
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