I campi id, relativi alle primary keys non si possono cancellare?

Es. ho un record con id=>1 e un altro con id=>2.
Se faccio un Class.delete(2) o anche un Class.destroy(2) (non mi
chiara la differenza tra i due) e poi inserisco un altro record noto
che gli viene assegnato id=>3.
E il 2 che fine ha fatto?

Il giorno 11/feb/09, alle ore 22:23, Mauro ha scritto:

Es. ho un record con id=>1 e un altro con id=>2.
Se faccio un Class.delete(2) o anche un Class.destroy(2) (non mi
chiara la differenza tra i due) e poi inserisco un altro record noto
che gli viene assegnato id=>3.
E il 2 che fine ha fatto?

E` stato cancellato non era quello che volevi?

Le primary key sono di default numeri autoincrementali. Ovvero ogni
nuovo oggetto eassociato ad una row nel db identificata da un numero intero che appunto e assegnato in automatico come (numero
precedente + 1).

Ci sono molti buoni motivi per avere questo schema ma se ti da
fastidio puoi scegliere la primary key come preferisci. Lo schema
precedente garantisce l’unicita’ (anche in presenza di query
parallele), ovviamente il tuo custom deve fare lo stesso.

Per farlo definisci un metodo before_create dove fai self.id = id
secondo le tue preferenze

Per quanto riguarda la differenza tra delete e destroy.

ri ActiveRecord::Base::delete

delete(id)
Delete an object (or multiple objects) where the +id+ given matches
the primary_key. A SQL +DELETE+ command is executed on the
database
which means that no callbacks are fired off running this. This is
an efficient method of deleting records that don’t need
cleaning up
after or other actions to be taken

Quindi delete e` associato ad un comando SQL DELETE

ri ActiveRecord::Base#destroy

Destroy an object (or multiple objects) that has the given id, the
object is instantiated first, therefore all callbacks and filters
are fired off before the object is deleted. This method is less
efficient than ActiveRecord#delete but allows cleanup methods and
other actions to be run.

  This essentially finds the object (or multiple objects) with the
  given id, creates a new object from the attributes, and then calls
  destroy on it.

Quindi destroy e` associato all’ORM, ovvero viene ricercata la riga
corrispondente all’id, instanziata una instanza della classe Ruby
associata a tale riga, e chiamato il delete su di esso. Meno
efficiente ma permette di usare tutta la infrastruttura OO di Rails.