janosrusiczki
janosrusiczki

Reputation: 1931

Creating multiple associated records from a single form

I have a form which creates a Listing - but I want it to create some associated records. My models are structured as follows:

When I submit this form I want to create a Listing, a Card and a Company in one shot. Also validations should be run.

Now I understand that if I want to include a Card field in my Listing form I'll use something like:

@card = @listing.cards.build
[...]
fields_for(@listing, @card) do |c|

But what should I do if I want to include Company fields in the form? I checked, but @card.company is nil.

Upvotes: 1

Views: 595

Answers (2)

Yan Foto
Yan Foto

Reputation: 11378

Short answer:

building a card doesn't automatically create an associated company

Long answer

The most reasonable way IMHO would be to start with the company and create associations around it even if you want to create a listing.

See it this way:

  • listing and company can exist on their own
  • card presupposes the existence of a company
  • a listing and a card are associated through a join table

Ergo: if you want to create a listing that has an associated card, you would also need a company to which that card belongs. Thus we would put the company on top of the hierarchy and do something like this:

class CompanyController < ApplicationController
  ...
  def new
    @company = Company.new
    @card = @company.cards.build
    @listing = @card.listings.build
  end
  ...
end

Respectively in your nested form you will have the company at the top, card next and listing at last:

= form_for @company do |company_f|
  - # company stuff
  = company_f.fields_for @card do |card_f|
    - # card stuff
    = card_f.fields_for @listing do |listing_f|
      - # listing stuff

Upvotes: 1

Pavel S
Pavel S

Reputation: 1543

You should use fields_for form helper http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for

Or use gems like https://github.com/ryanb/nested_form

Upvotes: 0

Related Questions