README.mdown in association_callbacks-0.0.2 vs README.mdown in association_callbacks-0.1.0
- old
+ new
@@ -24,11 +24,11 @@
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))
+ post.update_attributes!(last_comment_at: post.comments.order('created_at').last.try(:created_at))
end
end
But, there is a problem here: we define `Post` denormalization callbacks into
`Comment` model. IMHO, this is the wrong place. `Post` denormalization
@@ -38,15 +38,15 @@
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
+ 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))
+ update_attributes!(last_comment_at: comments.order('created_at').last.try(:created_at))
end
end
You just have to specify `:source` option to your callbacks, and that's all!
Note that `:source` option must be an existing association name.
@@ -58,19 +58,19 @@
has_many :comments
after_create :update_last_comment_at
def update_last_comment_at(comment)
- update_attributes!(:last_comment_at => comment.created_at)
+ 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|
+ after_destroy source: :comments do |post|
post.decrement!(:comments_count)
end
end
Another solution is to use [ActiveModel Observers](http://api.rubyonrails.org/classes/ActiveModel/Observer.html),
\ No newline at end of file