Search code examples
htmlruby-on-railsrubylink-to

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

How should I use link helper to get rid of the problem?


Solution

  • Just add an as: option on the routes.

    // 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 %>