Created
July 28, 2008 18:17
-
-
Save joshuaclayton/2928 to your computer and use it in GitHub Desktop.
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
# 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