I’m having trouble wrapping my head around this issue.
I have a business model and an address model. To make things more complicated, I also have a location model. A business can have multiple locations, but only one mailing address.
Here is a simple object chart.
Business
-Name
-MailingAddress
Location
-Business
-Name
-Address
I want to reuse the Address model for both the Businesses & Locations. What do I need to do for this. If it helps, I’m using MySQL.
First how to I structure the models? Do I need has_many :location,:business (for Location/Business)?
Then how do I nest the forms for creating addresses into new Business/Location forms.
Thanks!
I’ll start with some basic model code, then move onto controller, then views.
First the models:
Now the controller new action:
Finally the views:
address partial:
location partial:
There are a couple trickier components in this whole thing. You have to keep in mind that building a has_one and a has_many child object is a different method in the controller. Also, you need to define the class properly for the mailing address relationship.
If you wanted populate the business mailing address from a collection of the locations associated with the businesses addresses, then you could add a method in the Business model that did something like this: