Grouped Scope plugin

Plugin details

Extends has_many associations to group scope.

Websitehttp://github.com/metaskills/grouped_scope/tree/master Repositorygit://github.com/metaskills/grouped_scope.git Author Ken Collins Tags scope LicenseMIT

Documentation

Install the plugin:
ruby script/plugin install git://github.com/metaskills/grouped_scope.git

To use GroupedScope on a model it must have a :group_id column.

  class AddGroupId < ActiveRecord::Migration
    def self.up
      add_column :employees, :group_id, :integer
    end
    def self.down
      remove_column :employees, :group_id
    end
  end


Assume the following model.

  class Employee < ActiveRecord::Base
    has_many :reports
    grouped_scope :reports
  end


By calling grouped_scope on any association you create a new group accessor for each instance. The object returned will act just like an array and at least include the current object that called it.

  @employee_one.group   # => [#< Employee id: 1, group_id: nil>]


To group resources, just assign the same :group_id in the schema. Note that in future versions I will be extending the GroupedScope::Grouping that each object belongs to. If you do not just want to assign some random integers, then take a look at that model and the belongs_to :grouping code, schema needed ofcourse

  @employee_one.update_attribute :group_id, 1
  @employee_two.update_attribute :group_id, 1
  @employee_one.group   # => [#< Employee id: 1, group_id: 1>, #< Employee id: 2, group_id: 1>]


Calling grouped_scope on the :reports association leaves the existing association intact.

  @employee_one.reports  # => [#< Report id: 2, employee_id: 1>]
  @employee_two.reports  # => [#< Report id: 18, employee_id: 2>, #< Report id: 36, employee_id: 2>]


Now the good part, all associations passed to the grouped_scope method can be called on the group proxy. The collection will return resources shared by the group.

  @employee_one.group.reports   # => [#< Report id: 2, employee_id: 1>,
                                      #< Report id: 18, employee_id: 2>,
                                      #< Report id: 36, employee_id: 2>]


You can even call named scopes defined on the objects in the collection and association extensions defined on the original has_many. For instance:

  @employee.group.reports.urgent.assigned_to(user)

Further Documentation

There is currently no advanced documentation for this plugin.

New documentation

Edit plugin | Back in time (1 older version) | Last edited by: hardway, about 1 month ago