我在理解如何在 rails 中設定路由以將物件傳遞到 url helper 時遇到問題。
我添加了一個新方法 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
我添加了相應的路由
resources :hospitals do
member do
post :add_item
end
end
但是當我運行我的測驗時
post add_item_hospital_url(@hospital), params: { item: { item_code: item.item_code, description: item.description, gross_charge: item.gross_charge } }
測驗中的@hospital 不是 nil,而是在控制器上。我究竟做錯了什么?我的路線似乎沒問題
add_item_hospital POST /hospitals/:id/add_item(.:format)
uj5u.com熱心網友回復:
該實體變數@hospital是nil在控制器,因為它沒有被設定。也許你可以添加一個before_action來設定實體變數的值或者只是將它添加到add_item方法中。
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/390025.html
