Search code examples
mysqlruby-on-railsactiverecordafter-create

after_create in Rails with manual SQL query


I'm trying to create an object after another object is created, however the latter object is created using a SQL query rather than an ActiveRecord query.

I am trying to create an EventCode when a new instance of xyz is created as below:

class xyz < abc

  after_create :create_event_code

  def create_event_code
    event = UtilityDrEvent.find(self.utility_dr_event_id)
    participant = ParticipantAccount.find(self.participant_account_id)
    EventCode.generate_and_save(event, participant)
  end
end

But new instances of xyz are created thus:

insert_sql = 'INSERT INTO xyz (a_id, b_id)'

So the after_create method is never called. How can I get this to work?


Solution

  • ActiveRecord triggers are called only when you create a model using ActiveRecord itself. It doesn't have any code that observes the change in database. So if you want trigger the creation in another table you need to place the insert triggers in your database itself.

    Try this gem https://github.com/jenseng/hair_trigger this would help you write triggers to you database from within your rails code.