README.mdown in association_callbacks-0.2.0 vs README.mdown in association_callbacks-0.2.1
- old
+ new
@@ -9,24 +9,24 @@
First, two simple `Article` and `Comment` models:
class Article < ActiveRecord::Base
has_many :comments
end
-
+
class Comment < ActiveRecord::Base
belongs_to :article
end
Then, you often need to denormalize `Comment` stuff into `Post` or vice versa.
Here is the standard way to denormalize `last_comment_at` on posts:
class Comment < ActiveRecord::Base
belongs_to :article
-
+
after_create :update_post_last_comment_at
after_destroy :update_post_last_comment_at
-
+
def update_post_last_comment_at
post.update_attributes!(last_comment_at: post.comments.order('created_at').last.try(:created_at))
end
end
@@ -37,14 +37,14 @@
Here is how to do it with `association_callabacks`:
class Post < ActiveRecord::Base
has_many :comments
-
+
after_create :update_last_comment_at, source: :comments
after_destroy :update_last_comment_at, source: :comments
-
+
def update_last_comment_at
update_attributes!(last_comment_at: comments.order('created_at').last.try(:created_at))
end
end
@@ -54,23 +54,23 @@
Note that association callbacks methods can take associated record as
argument, above code can be:
class Post < ActiveRecord::Base
has_many :comments
-
+
after_create :update_last_comment_at
-
+
def update_last_comment_at(comment)
update_attributes!(last_comment_at: comment.created_at)
end
end
Association callbacks can also be defined as block:
class Post < ActiveRecord::Base
has_many :comments
-
+
after_destroy source: :comments do |post|
post.decrement!(:comments_count)
end
end
@@ -88,6 +88,6 @@
Then, just run `bundle install`.
## Executing test suite
This project is fully tested with [Rspec 2](http://github.com/rspec/rspec).
-Just run `bundle exec rake` (after a `bundle install`).
\ No newline at end of file
+Just run `bundle exec rake` (after a `bundle install`).