Creating forms for relational data in Rails
-
22-07-2019 - |
Question
I have a form that I need to display for a table that has a relationship with a couple of other tables. For instance, I have a table "cases" (think, investigator case), that has_one claimant and has_one client.
I would like the form to display the fields to fill out for the case data, client data and claimant data. Is there an easy way to do this so that when it's submitted, it would be as simple as:
case = Case.new(params[:case])
case.save
As it would be if I was just submitting and saving a form for only the case data?
Solution
Sounds like you are looking for the accepts_nested_attributes_for
method of activerecord. You will need to craft your form using
- form.fields_for :claimant do |claimant_form|
= claimant_form.text_field :name
You can find much more information in Ryan Daigle's blog post
OTHER TIPS
I don't believe there's a way where you can just call case.save and it'll work.
To make the form, look into using fields_for. http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#M001605
fields_for allows you to add fields that are stored in different POST variables, so if you set up the fields correctly then in your new method you could potentially do something like this:
claimant = Claimant.new(params[:claimant])
claimant.save
Which isn't terribly more complicated.
See my complex-form-examples on creating nested multi-model forms. This has been updated to work with Rails 2.3's accepts_nested_attributes_for
.
It allows you to nest the associations all under params[:case]
like you want. When you call case.save
everything else will be saved too.