Skip to content

Instantly share code, notes, and snippets.

@brandon-beacher
Created May 18, 2009 15:29
Show Gist options
  • Save brandon-beacher/113559 to your computer and use it in GitHub Desktop.
Save brandon-beacher/113559 to your computer and use it in GitHub Desktop.
module Primaryable
def self.included(base)
base.before_create :create_primary
base.before_destroy :destroy_primary
base.before_save :save_primary
base.before_update :update_primary
base.named_scope :primary_first, { :order => "`primary` desc" }
base.named_scope :primary_last, { :order => "`primary` asc" }
end
def siblings
primaryable_siblings
end
private
def create_primary
self.primary = true if siblings.empty?
end
def destroy_primary
siblings.first.update_attribute :primary, true if primary? && siblings.present?
end
def original_primary
new_record? ? nil : self.class.find(id).primary
end
def primary_changed?
primary != original_primary
end
def primaryable_siblings
super
end
def save_primary
self.class.update_all "`primary` = 0", "id in (#{sibling_ids.join(', ')})" if primary? && siblings.present?
end
def secondary?
!primary?
end
def sibling_ids
siblings.collect(&:id)
end
def update_primary
if siblings.empty?
self.primary = true
else
siblings.first.update_attribute :primary, true if primary_changed? && secondary?
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment