Home > Software engineering >  How do I pass an object in the rails URL helper
How do I pass an object in the rails URL helper

Time:12-23

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 seems to be fine

add_item_hospital POST   /hospitals/:id/add_item(.:format)

CodePudding user response:

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.

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
  • Related