Created
July 2, 2012 19:40
-
-
Save nicholasjhenry/3035215 to your computer and use it in GitHub Desktop.
Streamlined ActiveRecord
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 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