0

In my circuit.rb class I have the following

class Circuit < ActiveRecord::Base

  after_create :create_service

  def create_service
    # create service record
    service = Service.new :service_type => 'Circuit', :child_id => self.id, :organisation_id => self.organisation_id
  end

I only want the callback to fire when the circuit is created, I've tried before_validation aswell, no errors in the log, in fact, there is no mention of the services table being touched, I've restarted the server aswell just as a precaution but not sure why the service instance isn't being saved.

For completeness:

class CircuitController < ApplicationController
  def update
    ...
    if request.post?
      if @circuit
        # update
      else
        # attempt create
        @circuit = Circuit.new params[:circuit]
        if @circuit.save
          redirect_to :action => 'update', :id => @circuit.id
        end
      end
    end
  end
end

Also, all columns in the table allow NULL, except the id column which is AUTO_INCREMENT anyway so there's nothing on the database side that would prevent a record being saved, similarly there is no validation in the model and the circuit is saved properly.

martincarlin87
  • 10,848
  • 24
  • 98
  • 145
  • try `Service.create` instead of `Service.new`… – j03w Oct 03 '13 at 13:38
  • You should consider not creating a new resource inside your `update` method but in a `create` method. – Pierre-Louis Gottfrois Oct 03 '13 at 13:39
  • Thanks j03w, yeah, completely missed that one, Pierre, yeah I prefer it that way too, this is a legacy code base and all the update/create part of the CRUD is done via an update action. – martincarlin87 Oct 03 '13 at 13:53
  • You can also refer to the information in [this post](http://brettu.com/ruby-ruby-tips-210-confirm-before_save-callback-on-create/) if you want to be certain that your callback is firing only on either create or update. – James Chevalier Oct 03 '13 at 13:53

1 Answers1

3

Your callback is probably firing properly. The problem is that you're setting up a new Service, but not actually saving it. When your controller redirects, the Circuit object is reloaded and loses the Service object.

You probably want to actually create the object:

service = Service.create :service_type => 'Circuit', :child_id => self.id, :organisation_id => self.organisation_id
Dylan Markow
  • 123,080
  • 26
  • 284
  • 201