Reputation: 460
is a little project and I try to associate patient model with consultations. one patient has_many :consultations, in my form I have:
<%= f.association :patient %>
I pass the id parameter from the patient to the action 'new' in this way:
<%= link_to new_consultum_path(:id => @patient.id) %>
And in the view I have:
How can I make that the f.association field take the correspondent patient_id automatically?
How can I be sure that the patient_id is the current patient?
If I want to hide this field is that ok if I put
instead ofIs a better way to do this?
And why in the view shows me # patient:0x007f4e7c32cbd0 ?
thanks for your help.
Upvotes: 1
Views: 66
Reputation: 331
You want to associate consultations to patients using fields_for, which is similar to form_for, but does not build the form tags.
It you start with your patient object, you can iterate through the consultation associations binding it to form fields as you go.
it would look something like this
<%= form_for @patient do |patient_form| %>
<% patient_form.text_field :any_attribute_on_patient %>
<% @patient.consultations.each do |consultation| %>
<%= patient_form.fields_for consultation do |consultation_fields| %>
<% consultation_fields.text_field :any_attribute_on_consulatation %>
<% end %>
<% end %>
<% end %>
Sorry, the code may not be exactly right.
Check out the docs for field_for here
You will also have to set accepts_nested_attributes_for consultations on patient. When you set accepts_nested_forms_for, Rails will automatically update the associated consultations object to the patient and save any edits you have made. You DEFINITELY want to use accepts_nested_attributes_for most nested form handling of this type.
Upvotes: 0
Reputation: 76774
And why in the view shows me #
patient:0x007f4e7c32cbd0
This is a Patient
object.
It means you need to call an attribute of this object - EG @patient.name
.
--
f.association field
take the correspondentpatient_id
automatically
This might help:
It looks like Organization model doesn't have any of these fields: [
:to_label
,:name
,:title
,:to_s
] soSimpleForm
can't detect a default label and value methods for collection. I think you should pass it manually.
#app/models/patient.rb
class Patient < ActiveRecord::Base
def to_label
"#{name}"
end
end
Apparently, you need to have either title
, name
or to_label
methods in your model in order for f.association
to populate the data.
-
How can I be sure that the patient_id is the current patient?
If you're having to verify this, it suggests inconsistencies with your code's structure. If you need the patient_id
to be set as the current patient
, surely you could set it in the controller:
#app/controllers/consultations_controller.rb
class ConultationsController < ApplicationController
def create
@consultation = Constultation.new
@consultation.patient = current_patient
@consultation.save
end
end
I can provide more context if required.
Upvotes: 1