Dynamic nested form in Rails -
i have rails 3.2.22 app i'm maintaining , need create quasi-complex form. it's form records medications report.
so thought build model called narcoticusage contain record associated/nested model called narcotic actual model drug names.
i need somehow within narcotic usage form include functionality add multiple instances of narcotic model. ie. form have drug name (from narcotic model), expiration date , serial numbers of drugs (stored in narcoticusage). in form i'd able click "+" sign or add multiple drugs. in essence if recorded tylenol, cough syrup, ativan add dynamic field fill in drug name (from narcotic), enter expiration date , serial numbers associated narcoticusage model.
i have ideas on how design models , forms using nested_attributes i'm not sure best way design is.
any thoughts on best practices nested_forms?
thanks in advance , if need clarification or sample code, please let me know.
update: here proposed model schema
narcotic_usage.rb
has_many :narcotics attr_accessible :narcotic_id, :lot_number, :expiration_date
narcotic.rb
belongs_to :narcotic_usage attr_accessible :name
i'm not sure if need nested forms this. have drag/add in divs representing narcotics, each of has hidden field name set "narcotic_usage[narcotic_ids][]" , value id of narcotic.
then, when form submitted, ids of of these automatically go array accessed via params[:narcotic_usage][:narcotic_ids]
, can update @narcotic_usage
object params[:narcotic_usage]
in usual way. 1 of methods given has_many
macro narcotic_ids=
, expects called array of narcotic ids.
in other words, if have tylenol id 123 , ativan id 456, doing this:
@narcotic_usage.narcotic_ids = [123,456] @narcotic_usage.save
then rails make associations in database. form's params need hook this.
Comments
Post a Comment