Skip to content

Instantly share code, notes, and snippets.

@nicholasjhenry
Created July 2, 2012 19:40
Show Gist options
  • Select an option

  • Save nicholasjhenry/3035215 to your computer and use it in GitHub Desktop.

Select an option

Save nicholasjhenry/3035215 to your computer and use it in GitHub Desktop.
Streamlined ActiveRecord
class Post < ActiveRecord::Base
has_many :comments
# SERVICES
def comment(attributes)
create_comment(attributes)
end
# COLLABORATION METHODS
def create_comment(attributes)
Comment.new(attributes.merge(post: self))
end
# COLLABORATION RULES
def add_comment?(comment)
constrain_number_of_comments
end
def constrain_number_of_comments
errors.add_to_base("Cannot exceed 10 comments") if comments > 10
end
end
class Comment < ActiveRecord::Base
belongs_to :post
before_validation :verify_collaborations_rules
def verify_collaboration_rules
self.add_post?(post)
post.add_comment?(self)
end
# COLLABORATION RULES
def add_post?(post)
true
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment