-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Relation < ActiveRecord::Base | |
belongs_to :from, polymorphic: true | |
belongs_to :to, polymorphic: true | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SampleUsage < ActiveRecord::Base | |
include RelationExtensions | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
kur