0

I'm building a property management (apartments) application in Rails 3.2. Both units and properties have amenities. A property may have amenities like "On bus route" and "Coin op laundry" and a unit may have amenities like "Air conditioning" and "Handicap accessible". I had originally named my property amenities resource table amenities and the join table amenities_properties. However, now that I'm starting to build my amenities table for units I'm not sure how I should name these. I could go with amenities_properties and amenities_units. But then do I call the join tables amenities_properties_properties and amenities_units_units? Seems weird to me.

Would it maybe be better to have an amenities table that had a type field to indicate if it belongs to units or properties?

Ryan Arneson
  • 1,323
  • 3
  • 14
  • 25

1 Answers1

0

I would make amenities polymorphic, so it would look something like this:

amenity.rb

#There's not a grammatically good way to turn "amenity" into a polymorphic name so... 
belongs_to :amenitable, :polymorphic => true

property.rb and unit.rb

has_many :amenities, :as => :amenitable

Making amenities polymorphic adds an amenitable_type and amenitable_id column to the amenities table.

So when you create a new amenity, set the amenitable_type to either 'unit' or 'property' (depending on your model names), and the amenitable_id to the id of the unit or property to which it belongs.

n_i_c_k
  • 1,504
  • 10
  • 18
  • This looks nice, and I watched the revised RailsCasts on Polymorphic Associations. I started working though it and am not quite sure if this will work. Amenities aren't like comments where a user just types one in. An amenity is a resource that they select from in a drop down or checkboxes. So amenities for units and properties are stored in a resource table and generally don't change. Would polymorphic associations still work in this case? Would I want an approach similar to this SO post? http://stackoverflow.com/questions/6964678/habtm-polymorphic-relationship – Ryan Arneson Jun 05 '12 at 15:16
  • I guess conceptually I would use has_many_through when the relationship itself is important, like if you have users and magazines, the relationship (i.e. subscriptions) is important. Functionally though, I think has_may_through and polymorphic relationships are identical, info is just accessed a little differently. The only thing left is performance optimization, which I don't know enough about, so I'll leave that to someone else to answer. – n_i_c_k Jun 07 '12 at 00:28