Search code examples
ruby-on-railspostgresqltriggerspg

How create postgres trigger in rails?


I have a table product(id,name) and table product_raiting(product_id,rate_type,rate). When I create new product, I need to create three raitings for this product.

How can I add postgres trigger with do something like:



    product.create
    product.product_raitings.create( :rate_type => 0, :rate => 0 )
    product.product_raitings.create( :rate_type => 1, :rate => 0 )
    product.product_raitings.create( :rate_type => 2, :rate => 0 )
    product.product_raitings.create( :rate_type => 3, :rate => 0 )

Please help.


Solution

  • Do you want to create a trigger in the Database so on insert the DB does the work?

    http://www.postgresql.org/docs/9.1/static/sql-createtrigger.html

    CREATE FUNCTION addRaitings() RETURNS TRIGGER AS '
       BEGIN
          INSERT INTO product_raitings(product_id,rate_type,rate) values(NEW.id,0,0);
          INSERT INTO product_raitings(product_id,rate_type,rate) values(NEW.id,1,0);
          INSERT INTO product_raitings(product_id,rate_type,rate) values(NEW.id,2,0);
          INSERT INTO product_raitings(product_id,rate_type,rate) values(NEW.id,3,0);
       END;
       ' LANGUAGE plpgsql;
    
    CREATE TRIGGER createRaitingTrigger
            AFTER INSERT ON products
            FOR EACH ROW
            EXECUTE PROCEDURE addRaitings();
    

    or do you want rails to do the work? then it would be an after_create callback http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

    so perhaps something like this.

    class Product < ActiveRecord::Base
      has_many product_raitings
    
      after_create :build_default_raitings
    
     private
     def build_default_raitings
        (0..3).each { |x| self.product_raitings.create(:rate_type => x, :rate => 0) }
     end
    end