Performance: Association callbacks
This affects server response time and database transaction speed during object creation or update involving associated records.
class Order < ApplicationRecord has_many :items after_add :enqueue_processing def enqueue_processing(item) ProcessingJob.perform_later(item.id) end end
class Order < ApplicationRecord has_many :items after_add :heavy_processing def heavy_processing(item) # complex calculations or external API calls sleep(2) # simulating delay end end
| Pattern | Database Calls | Transaction Blocking | Server Response Time | Verdict |
|---|---|---|---|---|
| Heavy logic in association callbacks | 1+ per callback | Blocks until complete | High latency | [X] Bad |
| Light callbacks delegating to background jobs | 1 minimal call | Non-blocking | Low latency | [OK] Good |
after_add and after_remove callbacks in Rails associations?after_add and after_remove callbacks to trigger code when associated records change.after_add callback to a has_many association named comments in a Rails model?after_add: :method_name.has_many :comments, after_add: :notify_comment_added.comment is added to a Post?
class Post < ApplicationRecord
has_many :comments, after_add: :log_comment_added
def log_comment_added(comment)
puts "Comment added: #{comment.body}"
end
end
post = Post.new
post.comments << Comment.new(body: 'Nice post!')after_add callback calls log_comment_added with the new comment when added.after_remove callback:
class User < ApplicationRecord
has_many :posts, after_remove: :notify_post_removed
def notify_post_removed
puts 'Post removed'
end
endafter_remove receive the removed record as an argument.notify_post_removed has no parameters, so it will cause an error.Article model using has_many :tags. You want to update a counter on Article each time tags change. Which is the best way to implement this using association callbacks?after_add and after_remove on has_many :tags run code exactly when tags change.before_save is less direct and can miss changes; manual calls are error-prone.Pass the test and this pattern moves unknown