views:

48

answers:

1

I have one model say user, that can live in multiple towns (represented as another model). If I create a new user I have to choose (and edit) the different towns that they live in. Due to time constraints, I often end up with a "hackyier than I would like" solution involving something like: http://blog.hasmanythrough.com/2006/4/20/many-to-many-dance-off.

Any nice solutions that are popular with SO?

cheers...

Slothishtype

A: 

The has_and_belongs_to_many association was built for this very situation. Here is the documentation on it: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many

Otherwise, if you need to store information abotu the association itself (fields that would not exist in the city table or the user table, but in between), you might just want to set up two, parallel 'has_many_through' associations, and set up a seperate 'user_city' table. So it would be in the user table

has_many :user_cities
has_many :cities, :through => :user_cities

and in the cities table

has_many :user_cities
has_many :users, :through => :user_cities

Then, you CAN just call: user.cities, and get a list of the cities the user lives in.

jasonpgignac
I use has many through but end up with some messy code when creating the relationship. For example, I have sites and period associated with siteperiod. In my controller "create action" I implement something like:#Add the periodsif(params[:periods])#Delete Current Periodsfor siteperiod in @site.siteperiods siteperiod.destroyendfor period_id in params[:periods] siteperiod = Siteperiod.new siteperiod.period_id = period_id siteperiod.site_id = @site.id siteperiod.saveendendThis leaves me with a fat ugly controller; all very un-rails-like.Cheers...Slothistype
slotishtype
Wait, I don't think I understand - if in this example site has and belongs to many periods through site_period, then why would you automatically want to delete a site, if it wasn't associated to the period anymore? If you DID , you could make it dependent, and it would delete on it's own, I suppose, but I'm thinking I must be missing something?
jasonpgignac