Home Ask Login Register

Developers Planet

Your answer is one click away!

shakycode February 2016

Dynamic nested form in Rails

I have a Rails 3.2.22 app that I'm maintaining and I need to create a quasi-complex form. It's a form that records medications into a report.

So my thought is to build a model called NarcoticUsage to contain the record then an associated/nested Model called Narcotic which will be the actual model with the drug names.

I need to somehow within the Narcotic usage form include functionality to add multiple instances of the Narcotic model. ie. A form where you would have the drug name (from Narcotic model), then the expiration date and serial numbers of the drugs (stored in NarcoticUsage). In the form I'd like to be able to click a "+" sign or something like that to add multiple drugs. So in essence if someone recorded Tylenol, Cough Syrup, Ativan they could add a dynamic field to fill in the drug name (from narcotic), then enter the expiration date and serial numbers associated with the narcoticusage model.

I have some ideas on how to design the models and forms using nested_attributes but I'm not sure the best way to design this is.

Any thoughts on best practices with nested_forms?

Thanks in advance and if you need clarification or some sample code, please let me know.

Update: Here is my proposed model schema


has_many :narcotics
attr_accessible :narcotic_id, :lot_number, :expiration_date


belongs_to :narcotic_usage
attr_accessible :name


Max Williams February 2016

I'm not sure if you need nested forms for this. I would have it so that you drag/add in divs representing Narcotics, each of which has a hidden field with the name set to "narcotic_usage[narcotic_ids][]" and the value the id of that narcotic.

Then, when the form is submitted, the ids of all of these will automatically go into an array accessed via params[:narcotic_usage][:narcotic_ids] and you can then update your @narcotic_usage object with params[:narcotic_usage] in the usual way. One of the methods given to you by the has_many macro is narcotic_ids=, which expects to be called with an array of narcotic ids.

In other words, if you have Tylenol with id 123 and Ativan with id 456, then doing this:

@narcotic_usage.narcotic_ids = [123,456]

then rails will make the associations for you in the database. Your form's params just need to hook into this.

Post Status

Asked in February 2016
Viewed 3,766 times
Voted 5
Answered 1 times


Leave an answer

Quote of the day: live life