webForumDet fria alternativet

Ruby on Rails, callback-fråga (before_destroy)

Webbutveckling

1 svar · 585 visningar · startad av Peeer

Medlem sedan mars 20025 907 inlägg
Frågan#1

Hej!
Jag har en modell (Nodeequipment). I den har jag en before_destroy-callback...

before_destroy { |record| 
    Transaction.destroy_all "nodeequipment_id = #{record.id}"   
#    if Nodeequipment.count(:conditions => "nodeequipment_id = #{record.nodeequipment_id}") == 1
#      Nodeequipment.destroy_all "id = #{record.nodeequipment_id}"
#    end
  }

... som inte fungerar som den ska. Den första raden fungerar (Transaction.destroy_all), men inte de andra utkommenterade raderna. I felmeddelandet ser det ut som record.nodeequipment_id inte innehåller något värde (syntax error: SELECT count(*) AS count_all FROM "nodeequipments" WHERE (nodeequipment_id = )). Kan man inte plocka ut vilket attribut man vill ur ett record? IDt fungerar ju onekligen men inte det andra. Eller är det något annat jag missat?

Medlem sedan mars 20025 907 inlägg
#2

Tankevurpa. Koden resulterar i ett rekursivt anrop och toppföräldern har ett null-värde i nodeequipment_id, that's why!

before_destroy { |record| 
    Transaction.destroy_all "nodeequipment_id = #{record.id}"
    if record.nodeequipment_id.nil? == false
      if Nodeequipment.count(:conditions => "nodeequipment_id = #{record.nodeequipment_id}") == 1
        Nodeequipment.destroy_all "id = #{record.nodeequipment_id}"
      end
    end
  }
255 ms totalt · 4 externa anrop · v20260731065814-full.1dc6f849
124 ms — deklarationer (db)
0 ms — hämta statistik (cache)
129 ms — hämta tråd, inlägg och bilagor (db)
118 ms — ändringar (db)