Plugins - polymorphic_association
Add to favoritesUse-case:
Family and Person have some properties like Car, DVD, Book. They can own these or borrow from someone else, one silly restriction is Family can borrow Car, Person can't.
Here the solution:
class Family < ActiveRecord
polymorphically_has_many :items, :from => [:cars, :dvds, :books]
polymorphically_has :borrowed, :many => items, :from => [:cars, :dvds, :books]
end
class Person < ActiveRecord
polymorphically_has_many :ownables, :from => [:cars, :dvds, :books]
polymorphically_has :borrowed, :many => items, :from => [:dvds, :books]
end
class Book < ActiveRecord
polymorphically_has_one :owner, :through => ownables
polymorphically_has_one :borrower, :through => borrowed_items
end
And now
p = Person.create
p.ownables
p.ownables.dvds
p.ownables.cars
p.ownables.books
p.borrowed_items
p.borrowed_items.dvds
and pretty much the same for Family, and we also have
b = Book.find(:first)
b.onwer
b.borrower
Look at http://github.com/ducduong/polymorphic_association/tree/master for more details
http://github.com/ducduong/polymorphic_association/tree/master
git://github.com/ducduong/polymorphic_association.git
Rails' (MIT)
Model
