0

次の After Filters があります。

ユーザー モデル:

  def check_for_custom_district
    unless self.custom_district.blank?
      district = District.new(:name => custom_district, :state_id => state_id, :school_type_id => school_type_id)

      if district.save(false)
        school = School.new(:name => custom_school, :state_id => state_id, :country_id => 1, :source => "User")
        if school.save(false)
          district.schools << school
          update_attribute(:school_id, school.id)
        end
      end
    end
  end

  def check_for_custom_school
    if self.custom_district.blank? and self.custom_school.present?
      school = School.new(:name => custom_school, :state_id => state_id, :country_id => 1, :source => "User", :school_district_id => district_id)
      school.save(false)
      update_attribute(:school_id, school.id)
    end
  end

結果をコンソールに出力するためにデバッグを実行しましたが、コードがcheck_for_custom_districtメソッドにヒットし、何らかの理由で無限ループが発生しています。これを止める方法がわからない...何かアイデアはありますか?

4

1 に答える 1

1

after_saveフィルターだと思います。

それで、あなたがあなたのを保存したとしましょうmodel

after_saveフィルターをトリガーします。ただし、フィルターでは、実際には を呼び出しますupdate_attribute(:school_id, school.id)。これにより、現在のモデルも保存され、after_saveフィルターが再度トリガーされます。

それがあなたの無限ループの出所です。

after_saveこれを回避する 1 つの方法は、フィルターをまったく使用しないことです。たとえば、saveメソッドを再実装するだけです。

def save(*)
  # your custom logic goes here
  super
end
于 2012-10-17T17:18:55.973 に答える