views:

125

answers:

3

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?

A: 

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.

Karl
Well, I know that you can fill out an entire relational object like so: case = Case.new case.claimant = Claimant.new # Fill out case and claimant info case.saveAnd it will save the case and claimant stuff in the db properly... I just wasn't sure if you could do it with the params stuff from a form. I guess not. Thanks!
intargc
A: 

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

austinfromboston
Exactly what I was looking for! Thank you!
intargc
A: 

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.

ryanb