Skip to content

ActiveRecord Callbacks

larrylv edited this page Dec 8, 2014 · 2 revisions

This example uses callbacks to publish both creation successful and creation failed events.

Model

class Bid < ActiveRecord::Base
  include Wisper::Publisher

  after_create     :publish_creation_successful
  after_validation :publish_creation_failed, on: :create

  private

  def publish_creation_successful
    broadcast(:bid_creation_successful, self)
  end

  def publish_creation_failed
    broadcast(:bid_creation_failed, self) if errors.any?
  end
end

Controller

class BidsController < ApplicationController
  def create
    @bid = Bid.new(bid_params)
    @bid.on(:bid_creation_successful) { |bid| redirect_to bids_path }
    @bid.on(:bid_creation_failed)     { |bid| render action: 'new'  }
    @bid.save
  end
end