Satchel
Satchel

Reputation: 16724

How do I create a call back which runs after the final save in the create method in Rails?

I have the following create method for a Contact controller:

def create

    puts "in create method"
    @contact = Contact.create(params[:contact])

     unless @contact.vcard.path.blank?

           paperclip_vcard = File.new(@contact.vcard.path) 

       @vcard = Vpim::Vcard.decode(paperclip_vcard).first
       @contact.title = @vcard.title
       @contact.email = @vcard.email
       @contact.first_name = @vcard.name.given
       @contact.last_name = @vcard.name.family
       @contact.phone = @vcard.telephone
       @contact.address.street1 = @vcard.address.street
       @contact.address.city = @vcard.address.locality
       @contact.address.state = @vcard.address.region
       @contact.address.zip = @vcard.address.postalcode
       @contact.company_name = @vcard.org.fetch(0)

    end

    @contact.user_id = current_user.id # makes sure every new user is assigned an ID    
    if @contact.save
      #check if need to update company with contact info
      @contact.update_company

      flash[:notice] = "Successfully created contact."
      redirect_to @contact
    else
      render :action => 'new'
    end
  end

The callback I want to run should be done after the if @contact.save line at the very end of the method...but right now, it runs it in the first .create.

How do I allow a call back to run only after all the processing in the create method is completed?

Upvotes: 0

Views: 77

Answers (1)

Sergey
Sergey

Reputation: 795

Basically, ActiveRecord::Callback create(...) - Creates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.

You need to use (this is going from your script logic) instead:

 @contact = Contact.new(params[:contact])

If you want to callback save, use after_save callback.

Upvotes: 1

Related Questions