Plugins - polymorphic_association

StarAdd to favorites

Use-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

Duc Duong

http://github.com/ducduong/polymorphic_association/tree/master

git://github.com/ducduong/polymorphic_association.git

Rails' (MIT)

  • Currently 5.0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Model

Tags

Comments

Add a comment

Search Plugins

Query syntax

Plugins by Category

Sponsors

Rails Kits: Get Code. Get Moving.

Have a comment?