0

I currently have a few models, users, clients, addresses and contacts.

I used scaffold to create my client model which only contains name, leadsource and DBA. It is currently working just fine.

My address and contact was created separately as a client can have many addresses and contacts and they require a client_id to set up the relationship.

Assuming I am using your standard crud operations, is there any way to set up a single nested form that will allow me to add all 3 at once?

1 Answer 1

1

Sure, the standard way is fields_for.
But normally you also want to dynamically add and remove associated objects (i.e. addresses) and that's a bit more advanced.

There are gems to help you. i.e. cocoon and a great railscast: episode 403.

Unfortunately it's a pro episode, but investing the $9 is well worth it, as the railscasts really are a source of inspiration (at least for me).

I assume, you already have the associations or create them:

rails generate migration AddClientReferenceToAddress client:references
rake db:migrate

and in models:

class Client < ActiveRecord::Base
  has_many :addresses
end

class Address < ActiveRecord::Base
  belongs_to :client
end
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Martin! For removing objects together I would just add dependency into the relationship on the model, correct?
I've always debated signing up for railcast but I took your word on it and just went with it, Cacoon looks exactly like what I need! I appreciate the help!
unfortunately Ryan stoppt creating new railscasts more than two years ago. I hope he's fine.
Cocoon is magic! Took me a bit to figure it out as the documentation for your standard coding isn't very easily obtainable but once I got it running it's really cool. Have you ever tried to display cocoon in tabs? Is there an easy way to do this?
yes, I also use it in tabs, even several cocoons on one tab. Runs like charm. I use fieldsets to wrap the partials of one association and cocoon stay in this fieldset and doesn't disturb others. b.t.w think about accepting my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.