如何在rails中创建postgres触发器?

时间:2013-04-23 18:09:33

标签: ruby-on-rails postgresql triggers pg

我有一个表产品(id,name)和表product_raiting(product_id,rate_type,rate)。 当我创建新产品时,我需要为此产品创建三个raitings。

如何添加postgres触发器,例如:



    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 )

请帮忙。

1 个答案:

答案 0 :(得分:8)

您是否要在数据库中创建触发器,以便插入数据库是否可以正常工作?

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();

或者你想让rails做这项工作吗?然后它将是一个after_create回调 http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

所以也许是这样的。

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