10

Ho 2 modelli come descritto di seguito.Come si usa dipendente:: distruggere nelle guide?

class EmpGroup < ActiveRecord::Base 
    belongs_to :user 
    has_many :emp_group_members, dependent: :destroy 
end 

e

class EmpGroupMember < ActiveRecord::Base 
    belongs_to :emp_group 
    belongs_to :user 
end 

ora il problema è ogni volta ho cercato di distruggere un gruppo poi ho ricevuto un errore come di seguito.

PG::ForeignKeyViolation: ERROR: update or delete on table "emp_groups" violates foreign key constraint "fk_rails_bd68440021" on table "emp_group_members" 
DETAIL: Key (id)=(1) is still referenced from table "emp_group_members". 

Cosa mi manca?

Grazie.

risposta

12

Aggiungi a cascata eliminare al modello EmpGroup:

class EmpGroup < ActiveRecord::Base 
    has_many :emp_group_members, :dependent => :delete_all 
end 

O

Stai chiamando il metodo delete? dovresti chiamare lo destroy. Usa .destroy

1

Quando si elimina un gruppo, si utilizza elimina o distrugge. - Ho avuto questo errore prima, ed è stato perché ho avuto un errore di battitura e stavo usando .delete invece di .destroy

6

:dependent è una delle opzioni disponibili in belongs_to associazione

If you set the :dependent option to: 

:destroy, when the object is destroyed, destroy will be called on its associated objects. 
:delete, when the object is destroyed, all its associated objects will be deleted directly from the database without calling their destroy method. 

Additionally, objects will be destroyed if they're associated with dependent: :destroy, and deleted if they're associated with dependent: :cancella tutto.

in has_many associazioni:

:destroy causes all the associated objects to also be destroyed 
:delete_all causes all the associated objects to be deleted directly from the database (so callbacks will not execute) 

si può provare

emp_member_1= @emp_group.emp_group_members.first 
##delete associated record 
@emp_group.emp_group_members.delete(emp_member_1) 
Problemi correlati