You are here: Browse Railsplugins Acts As Relatable
= acts_as_relatable
Instructions Installation Usage = Prepare databaseGenerate and apply the migration:
ruby script/generate acts_as_relatable_migration
rake db:migrate
=== Basic related functionallity
Let’s suppose users have many posts and we want those posts to have related items. The first step is to add acts_as_relatable to the Post class:
class Post < ActiveRecord::Base
acts_as_relatable :related_fields=>{:title=>10, :description=>2},
:related_filter=>:filter_function
end
belongs_to :user
Also you can define as:
class Post < ActiveRecord::Base
acts_as_relatable :related_fields=>{:title=>10, :description=>2},
:related_models=>[:user]
end
belongs_to :user
In the first example, you have to implement the filter_function, which must return a list of objects where the related items will be found. In the second example there is no filter, so all users table will be matched.
The related_fields hash is a list of fields that will be used to find matches. This field is mandatory. The key of the hash is the name of the field you will use to match, and the value is the weight that you will use for each match. In the example, the title has a value of 10 and the description a value of 2. This means that the title will be more significative than the description, and items with the same title will match with a higher value than items with the same description.
Also you can use :related_extra param, which will point to a custom function of the model, which can be used to add custom items to the related_item_list:
class Post < ActiveRecord::Base
acts_as_relatable :related_fields=>{:title=>10, :description=>2},
:related_models=>[:user],
:related_extra=>:my_function
end
belongs_to :user
def my_function
result = []
result = result + item_a
result = result + item_b
return result
end
In this example, the objects item_a and item_b will also be added to the related_item_list attribute, althought the match function return 0.0.
We can now use the related methods provided by acts_as_relatable, #related_items, #relatable_items and all_related_items. Also you have the readonly method related_item_list, which it is an array with the instances of the related items.
The related items will be automatically updated when you save your object:
p = Post.find(:first)
p.find_related # [an array of related items]
p.related_item_list # [the same array than above]
p.save
=== Finding related objects
To retrieve objects related on a object, use find_related.
Post.find_related(threshold)
threshold value must be a value between 0.0 and 1.0. 1.0 means exact match. The default value for threshold is 0.2.
By default, find_related will find objects that are related (more than 0.2 threshold) to the current model.
=== Other
Problems, comments, and suggestions all welcome.
NOTE: This description has been extracted from the Plugin README and so the formatting may need updating to make browser friendly