0

使用 Mongoid 3,rails 3.2

我有这样的课

class Company
  include ActiveModel::ForbiddenAttributesProtection
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Slug
  ....
end

我有一个像这样的观察者

class CompanyObserver < Mongoid::Observer

  def after_create company
     ...
  end
end

我的问题是 after_create 回调被多次调用,有时最多 3 次,当我通过控制器或控制台创建公司时,它会调用两次回调。我已经测试以确保观察者没有被实例化两次。我也尝试过使用 before_create 并检查 new_record?第一次返回 true 第二次返回 false 所以我不知道它为什么第二次调用它。

这是我的 Companies 控制器,但是我想使用我的 after_create 回调,因为我只想在创建模型时调用它,而不是在更新模型时调用它

class CompaniesController < ApplicationController
  respond_to :html
  before_filter :set_company, only: [:edit, :update, :destroy]

  load_and_authorize_resource :company, except: [:create, :update]

  def index
    @companies = Company.all
  end

  def show
  end

  def new
    @company = Company.new
  end

  def create
    @company = Company.create(company_params)
    authorize! :create, @company
    @company.save
    respond_with(@company)
  end

  def edit
  end

  def update
    authorize! :update, @company
    @company.update_attributes(company_params)
    respond_with(@company)
  end

  def destroy
    if @company.destroy
      redirect_to root_url(subdomain: false)
    else
      redirect_to @company
    end
  end

  #######
  private
  #######

  def set_company
    @company = Company.find(params[:id])
  end

  def company_params
    params.require(:company).permit(:name)
  end

end
4

0 回答 0