HABTM best practice
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开发者_如何学C rails way'
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.
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
精彩评论