0

Have been dealing with this issue for some time and searched through the whole net, but nothing seems to be useful.

I'm trying to post data through a link_to tag like this:

// get_doctors.html.erb
<%= link_to "Ekle", patient_add_doctor_path(id: @patient.id), data: { doctor: doctor.id }, method: :post  %> 

However, at the controller, I can not reach the data in my controller.

// patients_controller.rb

def add_doctor
    patient = Patient.find(params[:id].to_i)
    doctor  = Doctor.find(params[:doctor].to_i) // problem is here!
    patient.doctors << doctor
end

It gives me the error that params[:doctor] is 0.

Couldn't find Doctor with 'id'=0 [WHERE "users"."type" IN ('Doctor')]

Have tried many different ways. Tried also this,

<%= link_to "Ekle", patient_add_doctor_path(id: @patient.id), doctor: doctor.id, method: :post  %> 

which is also did not worked.

Burak Özmen
  • 865
  • 2
  • 11
  • 28
  • try this `<%= link_to "Ekle", patient_add_doctor_path(id: @patient.id, doctor: doctor.id), method: :post %>` – Athar Jul 27 '15 at 18:12
  • this should give you some clearity http://stackoverflow.com/a/13414818/753705 – abhishek77in Jul 27 '15 at 18:16
  • I know it's ugly but you might have to render forms for each link you want to post data. Would definitely like to see a nicer way to do this. – abhishek77in Jul 27 '15 at 18:19
  • @abhishek77in I was going to do that but gave up for the same reason you have just stated :( – Burak Özmen Jul 27 '15 at 18:23
  • `link_to` with `method: :post` should be creating a form for you, with the data passed as hidden attributes. Your original link_to tag seems right. Can you inspect the rendered page and paste what HTML Rails is generating for your tag? – Robert Nubel Jul 27 '15 at 18:28
  • @Athar It worked like a charm. This may sound amateur but is it possible to pass them as hidden variables, without showing them in the URL? Just asking out of curiosity. – Burak Özmen Jul 27 '15 at 18:31
  • How you are getting doctor variable here `doctor.id`? – Pavan Jul 27 '15 at 18:32
  • as @abhishek77in said, you have to use form for that. create a form and set the doctor as hidden_field in it and the values will not be part of url. – Athar Jul 27 '15 at 18:33
  • @RobertNubel of course. Here is the generated HTML. `Ekle` – Burak Özmen Jul 27 '15 at 18:35
  • @Pavan by `@doctors.each do |doctor|` block. Forgot to include that, sorry. – Burak Özmen Jul 27 '15 at 18:44
  • @BurakÖzmen: oh, I see. The `data:` attribute doesn't specify attributes that will be sent with the request, but instead custom `data-foo` attributes on the `a` tag... which doesn't get you anywhere. Athar's suggestion is your best bet short of creating a form tag. – Robert Nubel Jul 27 '15 at 18:50

0 Answers0