What should one use to persist instance variables through different controller#actions, without using the session?
Here is an example of the problem:
There is an Hospitalization which has_one Prescription
From hospitalization#show I have a link_to prescription#new with additional parameters as seen bellow:
<%= link_to t('hospitalizations.prescription'), new_prescription_path(hospitalization_id: @hospitalization.id,...)
And the trick is: at prescription#new I can retrieve
@hospitalization = Hospitalization.find_by(id: params[:hospitalization_id])
But when I press submit and it comes to prescription#create, @hospitalization answers to nil when trying to do something like
@prescription = @hospitalization.build_prescription(prescription_params)
How would be the best way to instantiate these parameters so they persist or get easily carried between the controller#actions one needs? How should I instantiate the belonging model Prescription? Should I put the ID directly there, on prescription#new? Like:
@prescription = Prescription.new(hospitalization_id: params[:hospitalization_id])
Use neseted resources this way:
resources hospitalizations do
resource :prescription
end
This way your path is going to look like this:
/hospitalizations/:hospitalization_id/prescription
and you can use the following to generate it:
new_hospitalization_prescription_path(@hospitalization)
now in your controller you can access the parameter as params[:hospitalization_id]
. For example in the create
method of your PrescriptionController
:
def create
hospitalization = Hospitalization.find(params[:hospitalization])
prescription = Prescription.new(hospitalization: hospitalization, ...)
# ...
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.