Skip to content

Instantly share code, notes, and snippets.

@Emerson
Forked from AlexJWayne/has_relations.rb
Last active August 29, 2015 13:59
Show Gist options
  • Select an option

  • Save Emerson/11003922 to your computer and use it in GitHub Desktop.

Select an option

Save Emerson/11003922 to your computer and use it in GitHub Desktop.
Rewritten as a Rails concern with updated syntax. Also added a relation_identifier and relation_position that gets dynamically attached to related objects.
module RelationExtensions
extend ActiveSupport::Concern
included do
# -- Constants ------------------------------------------------------------
# -- Attributes -----------------------------------------------------------
attr_accessor :relation_identifier, :relation_position
# -- AR Extensions --------------------------------------------------------
# -- Relationships --------------------------------------------------------
has_many :relations, as: :from
# -- Validations ----------------------------------------------------------
# -- Scopes ---------------------------------------------------------------
# -- Callbacks ------------------------------------------------------------
# -- Class Methods --------------------------------------------------------
# -- Instance Methods -----------------------------------------------------
def related(params = {})
relation_type = params[:relation_type]
identifier = params[:identifier]
scope = relations.order(:position)
if relation_type.present?
scope = scope.where(to_type: relation_type.to_s.classify)
end
if identifier.present?
scope = scope.where(identifier: identifier)
end
scope.collect do |relation|
to = relation.to
to.relation_identifier = relation.identifier
to.relation_position = relation.position
to
end
end
def add_related(model)
raise ArgumentError, "Cannot add related object since it is not an ActiveRecord model" unless model.kind_of?(ActiveRecord::Base)
relations.create(to: model) unless related.member?(model)
model
end
end
end
class Relation < ActiveRecord::Base
belongs_to :from, polymorphic: true
belongs_to :to, polymorphic: true
end
class SampleUsage < ActiveRecord::Base
include RelationExtensions
end
Copy link
Copy Markdown

ghost commented Jan 21, 2015

kur

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment