acts_as_relatable
Installation
(This gem has only been tested with Rails 3 for the moment, compatibility with Rails 3.1 is coming soon)
Gem installation :
gem install acts_as_relatable
Or you can put it in your Gemfile :
gem "acts_as_relatable"
and then run :
bundle install
You’ll then need to run the migration generator for the Relationship model :
r generate acts_as_relatable:migration
Followed by :
rake db:migrate
Usage
class Recipe < ActiveRecord::Base
acts_as_relatable :product
end
class Product < ActiveRecord::Base
acts_as_relatable :recipe
end
@bread = Product.create(:name => "Bread")
@butter = Product.create(:name => "Butter")
@pancake = Recipe.create(:name => "Pancakes")
#Creating relationships
@butter.relates_to!(@pancake) # #<ActsAsRelatable::Relationship id: 2, relator_id: 1, relator_type: "Recipe", related_id: 2, related_type: "Product">
@bread.relates_to!(@butter) # #<ActsAsRelatable::Relationship id: 4, relator_id: 2, relator_type: "Product", related_id: 1, related_type: "Product">
#By default, relationships are both-sided, it means that on the first line above, @butter is related to @pancake, but @pancake is also related to @butter.
#If you don't want/need this behaviour, you can pass false as a second argument to the relates_to! instance method :
@butter.relates_to!(@pancake, false)
#Fetching relationships
@butter. # [#<Recipe id: 1, name: "Pancakes">]
@butter. # [#<Product id: 1, name: "Bread"]
@butter. # {:recipes=>[#<Recipe id: 1, name: "Pancakes">], :products=>[#<Product id: 1, name: "Bread">]}
#Testing relationships
@butter. @bread # true
@bread. @pancake # false
#Destroying relationships (This instance method destroys both relationships if it's a both-sided one)
@butter.destroy_relation_with @pancake
Contributing to acts_as_relatable
-
Check out the latest master to make sure the feature hasn’t been implemented or the bug hasn’t been fixed yet
-
Check out the issue tracker to make sure someone already hasn’t requested it and/or contributed it
-
Fork the project
-
Start a feature/bugfix branch
-
Commit and push until you are happy with your contribution
-
Make sure to add tests for it. This is important so I don’t break it in a future version unintentionally.
-
Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
TODOS
-
Rails 3.1 compatibility
-
Add a make_between method in Relationship model
-
Improve README
Copyright
Copyright © 2011 Malamitsas. See LICENSE.txt for further details.