[英]Undefined method by link_to helper
I need to post through a link tag, however there is a problem with the link helper. 我需要通过链接标记发布,但是链接帮助器存在问题。 Here is my link tag
这是我的链接标签
// doctors.html.erb
<%= link_to "Ekle", [:add_doctor, @patient], method: :post %>
And my routes.rb 还有我的routes.rb
// routes.rb
get 'patients/:id/doctors' => 'patients#get_doctors'
post 'patients/:id/doctors' => 'patients#add_doctor'
I get the error 我得到错误
undefined method `add_doctor_patient_path' for #<#:0x007fd39283a4b0> #<#:0x007fd39283a4b0>的未定义方法`add_doctor_ Patient_path'
How should I use link helper to get rid of the problem? 我应该如何使用链接助手来解决这个问题?
This line in your routes.rb
shows that you have a get_doctors
route that accepts one argument, :id
: routes.rb
中的这一行表明您有一条get_doctors
路由,它接受一个参数:id
:
get 'patients/:id/doctors' => 'patients#get_doctors'
That means you should use the corresponding path helper, get_doctors_path
, and pass it the Patient object: 这意味着您应该使用相应的路径助手
get_doctors_path
,并将其传递给Patient对象:
<%= link_to "Ekle", get_doctors_path(@patient), method: :post %>
PS Your routes are puzzling, since you could accomplish the same thing by using resourceful routes, as recommended by the Rails Guides , instead of defining your own custom get
and post
routes, and in so doing save yourself a lot of trouble: PS您的路线令人困惑,因为您可以按照Rails Guides的建议通过使用资源丰富的路线来完成相同的事情,而不是定义自己的自定义
get
和post
路线,从而省去了很多麻烦:
resources :patients do
resources :doctors
end
This would create eg patient_doctors_path
and new_patient_doctor_path
path helpers that would automatically route to your DoctorsController#get
and DoctorsController#new
methods, respectively, and it would enable you to use eg form_for [ @patient, :doctor ]
. 这将创建例如
patient_doctors_path
和new_patient_doctor_path
路径帮助器,它们将分别自动路由到您的DoctorsController#get
和DoctorsController#new
方法,并且使您能够使用例如form_for [ @patient, :doctor ]
。 PatientsController is very much the wrong place to put logic for retrieving and modifying Doctors. PatientController是放置用于检索和修改Doctor的逻辑的错误位置。
Just add an as: option on the routes. 只需在路线上添加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
Then in the view: 然后在视图中:
// doctors.html.erb
<%= link_to "Ekle", patient_add_doctor_path(id: @patient.id), method: :post %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.