'PostgreSQL function in Rails migration

I want to add a column to a PG database in Rails. The Topic model has_many :replies. Each topic/reply has an integer word_count. Can I calculate the word_count in the database, without touching the Rails code? I'd like to exclude the user who authored the topic.



Solution 1:[1]

You can use after_update callback in your topic.rb file to trigger a method every time the topics are updated.

after_update :update_word_count

def update_word_count
  self.update_column(:word_count, self.topic.split.count)
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 khalee