I have a Tournament model that needs 0, 1, or 2 contacts. I created a Contact model and set has_many :contacts on the Tournament and belongs_to :tournament on the Contact. The Tournament accepts_nested_attributes_for :contacts.
However, when I build the form for Tournament I don’t quite see how I should do it. I’m thinking about having two fields_for :contacts but it feels messy. I also considered having two specific attributes on the Tournament model (something along the line of primary_contact and secondary_contact) but I’m not sure about how to do that.
Is there a “correct” way to do this? Any suggestions?
I’m on Rails 3.1 BTW.
fields_for :contactsis the right way to go.Take advantage of the fact that, if
tournament.contactshas multiple items, then a singlefields_for :contactswill show multiple fieldsets.Then take advantage of the fact that
tournament.contacts.buildwill create an unsavedContactand add it to thecontactscollection. If you do this in the controller before showing the form then yourfields_forwill display this empty contact and use it correctly with its nested attributes