Eric Ponce
Eric Ponce

Reputation: 55

Moving from before_create to PostgreSql trigger?

We have models with with before_create triggers like this:

def set_location_id
  self.location_id = Location.find_by(code: location_code).id
end

def set_product_id
  self.product_id = Product.find_by(code: product_code).id
end

Do you think that could be a good idea to move those rails triggers to PostgreSql?

What about performance?

Upvotes: 2

Views: 51

Answers (2)

mdesantis
mdesantis

Reputation: 8517

I'll tell you some rules I currently adopt about performance optimizations:

  1. Always do performance optimizations when you have to
  2. Do performance optimizations only when you have to
  3. Always ensure you have the desired performance improvement measuring it on real data

And now the respective considerations:

  1. As far as I can understand you don't have the need of such that performance optimization
  2. As far as I can understand you don't have the need of such that performance optimization
  3. @Coderhs in its answer took for granted that you would have a performance improvement. My experience teached to me that assumed benchmark results often deviate from the real ones, and sometimes you even have a performance degradation. So I suggest you to 1) establish the desired performance improvement 2) measure it. Since as far as I can understand you don't have the need of such that performance optimization, probably you should spend your time implementing a feature or fixing a bug, or refactoring ;)

Upvotes: 0

coderhs
coderhs

Reputation: 4837

Using PostgreSQL's after or before insert triggers would definitely be faster and more efficient that Ruby(activerecord) before_create. But your code would become really hard to maintain. Now your softwares business logic would be at two different location 1) store procedure within the rails application 2) In your rails model

Having the two different location would make it hard to debug and program in future.

Upvotes: 1

Related Questions