Skip to content

Instantly share code, notes, and snippets.

@joshuaclayton
Created July 28, 2008 18:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshuaclayton/2928 to your computer and use it in GitHub Desktop.
Save joshuaclayton/2928 to your computer and use it in GitHub Desktop.
# With callback methods, if they return false, it will halt the chain and your model won't be saved.
# Ninety-nine out of a hundred times, this is only an issue if you're 'caching' a boolean value based on
# an association status or other convoluted evaluation
class Entity < ActiveRecord::Base
named_scope :publicly_available, :conditions => {:publicly_available => true}
has_many :items
belongs_to :user
before_save :calculate_publicly_available
attr_protected :publicly_available
protected
def calculate_publicly_available
self.publicly_available = self.items.any? && !self.user_id.nil?
# return true here or the callback chain will halt if the statement evaluates to false
true
end
end
class Item < ActiveRecord::Base
belongs_to :entity
validates_presence_of :entity_id
end
class ItemObserver < ActiveRecord::Observer
def after_create(item)
save_entity(item.entity)
end
def after_destroy(item)
save_entity(item.entity)
end
private
def save_entity(entity)
entity.save!
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment