3

I have 2 main entities, UserProfile and Property. Basically, the UserProfile needs to maintain 3 different lists of Properties (note, each list type will have additional properties)

Does anyone see anything wrong with the following design for doing so:

class UserProfile < ActiveRecord::Base
  has_many :shortlists
  has_many :booklists
  has_many :proplists
end

class Shortlist < ActiveRecord::Base
  has_and_belongs_to_many :properties
end

class Booklist < ActiveRecord::Base
  has_and_belongs_to_many :properties
end

class Proplist < ActiveRecord::Base
  has_and_belongs_to_many :properties
end

class Property < ActiveRecord::Base
  has_and_belongs_to_many :shortlists
  has_and_belongs_to_many :booklists
  has_and_belongs_to_many :proplists
end

The other way I was considering is to use polymorphism for the Property entity, but not sure which way would be more 'the rails way'

Mario
  • 2,942
  • 1
  • 25
  • 38
Sami Begg
  • 239
  • 2
  • 7
  • 1
    One of the keys of 'the rails way' is to avoid repeating yourself. You should use polymorphism to consolidate these lists as descendants of a `List` class. – Mario May 27 '11 at 15:36
  • 1
    Note that has_and_belongs_to_many will be deprecated and replced with has_many, :through – apneadiving May 27 '11 at 15:37

2 Answers2

1

HABTM is slightly out of date, and has been replaced with has_many :through. In addition check out the Railscast on Polymorphic Associations. Ryan Bates does an excellent job explaining this.

ardavis
  • 9,842
  • 12
  • 58
  • 112
0

Polymorphism seems like the right idea, of course. It's staring you right in the face. But if you go too far with it, I'd like to warn you away from the has_many_polymorphs gem. Out of date, buggy, the Rails 3 version isn't close to mature, and it makes your development environment extremely heavy (every request takes an extra 4-6 seconds to load).

Read up on polymorphism a bit more, like here:

http://quickleft.com/blog/advanced-activerecord-recipes-doubly-polymorphic-join-models

nessur
  • 1,143
  • 1
  • 11
  • 18