Your call to Group.increment_counter sends SQL like this to the database:
update groups set tasks_count = coalesce(tasks_counter, 0) + 1 where id = X
where X is @task.id The SQL way to get the new tasks_counter value is to include the RETURNING clause:
update groups set tasks_count = coalesce(tasks_counter, 0) + 1 where id = X returning tasks_count
I do not know what a convenient way Railsy get SQL in the database. The usual Rails approach would be to do a bunch of locking and reloading @task or skip the lock and hope for the best:
Group.increment_counter :tasks_count, @task.id @task.reload
You can use RETURNING like this:
new_count = Group.connection.execute(%Q{ update groups set tasks_count = coalesce(tasks_counter, 0) + 1 where id = #{Group.connection.quote(@task.id)} returning tasks_count }).first['tasks_count'].to_i
You probably want to hide this clutter behind a method on Group so you can say things like:
n = Group.increment_tasks_count_for(@task)
source share