簡體   English   中英

link_to幫助程序的未定義方法

[英]Undefined method by link_to helper

我需要通過鏈接標記發布,但是鏈接幫助器存在問題。 這是我的鏈接標簽

// doctors.html.erb
<%= link_to "Ekle", [:add_doctor, @patient], method: :post %> 

還有我的routes.rb

// routes.rb 
get    'patients/:id/doctors' => 'patients#get_doctors'
post   'patients/:id/doctors' => 'patients#add_doctor'

我得到錯誤

#<#:0x007fd39283a4b0>的未定義方法`add_doctor_ Patient_path'

我應該如何使用鏈接助手來解決這個問題?

routes.rb中的這一行表明您有一條get_doctors路由,它接受一個參數:id

get 'patients/:id/doctors' => 'patients#get_doctors'

這意味着您應該使用相應的路徑助手get_doctors_path ,並將其傳遞給Patient對象:

<%= link_to "Ekle", get_doctors_path(@patient), method: :post %> 

PS您的路線令人困惑,因為您可以按照Rails Guides的建議通過使用資源豐富的路線來完成相同的事情,而不是定義自己的自定義getpost路線,從而省去了很多麻煩:

resources :patients do
  resources :doctors
end

這將創建例如patient_doctors_pathnew_patient_doctor_path路徑幫助器,它們將分別自動路由到您的DoctorsController#getDoctorsController#new方法,並且使您能夠使用例如form_for [ @patient, :doctor ] PatientController是放置用於檢索和修改Doctor的邏輯的錯誤位置。

只需在路線上添加as:選項即可。

// routes.rb 
get    'patients/:id/doctors' => 'patients#get_doctors',as: :patient_get_doctor
post   'patients/:id/doctors' => 'patients#add_doctor', as: :patient_add_doctor

然后在視圖中:

// doctors.html.erb
<%= link_to "Ekle", patient_add_doctor_path(id: @patient.id), method: :post %> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM