Thomas Ayoub
Thomas Ayoub

Reputation: 29431

Destroy doesn't destroy

I've 3 models user formation & achat(let's translate to a sort of billing).

A user cand buy a formation, it will create an achat. For reasons I need to delete one achat. But I didn't succeed. I tried the following work-flow to check my code:

irb(main):048:0> u.achats.length
=> 1
irb(main):049:0> u.achats.first.destroy!
   (0.1ms)  BEGIN
   (0.1ms)  COMMIT
=> #<Achat id: 8, formation_id: 14, created_at: "2015-06-29 16:08:39", nom_formation: "foo", prix: 0.0, quantite: 1, chapitre_id: nil, user_id: 10, taux_commission: 35, updated_at: "2015-06-29 16:08:39", numero_facture: nil, bon_reduction_id: nil>
irb(main):050:0> u.achats.length
=> 1

So it isn't deleted from the database. How should I destroy the achat?


Here are a (simpler) version of my models:

# coding: utf-8
class User < ActiveRecord::Base
  rolify :role_cname => 'Role'
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  #Tous les achats de cette utilisateur
  has_many :achats
  #Toutes les formations achetés par cet utilisateur
  has_many :formations, :through => :achats
end


#Classe liant une formation à un utilisateur
class Achat < ActiveRecord::Base

  #Lien vers l'utilisateur qui a acheté cette formation
  belongs_to :user
  #Appartient à la classe Formation
  belongs_to :formation

end

#Classe récupérant les différentes informations liées à toutes les formations présentes pour le site
class Formation < ActiveRecord::Base

  #Auteur de cette formation
  belongs_to :user

  # Gestion de la relation pour l'achat
  has_many :achats

  #Si la formation est publique alors on ne fait que changer le statut et la date de suppression
  #Si la formation n'a jamais été publié, alors on la supprime totalement de la base
  def destroy
    #Si la formation est déja supprimée on bloque la chose
    if(self.status.id == 3)
      return FORMATION_DEJA_SUPPRIME
    else
      update_attribute(:status, Status.find(2))
    end
  end

  # Gestion de la suppression d'un produit
  def delete!
    update_attribute(:dateSuppression, Time.now)
  end
end

I've been through this question: dependent: :destroy doesn't work (has_many association) but it didn't helped...

Upvotes: 0

Views: 83

Answers (2)

Ojash
Ojash

Reputation: 1234

As @josh-burgess also pointed out, you could destroy and then reload the object.

u.achats.first.destroy!
u.achats.reload

Upvotes: 0

Alex Antonov
Alex Antonov

Reputation: 15146

Record variable still available even destroyed. Try

Achat.find(8) # or some another destroyed id

to make sure you have deleted the record from the database

P.S. Consider destroyed? method of rails for understanding

Upvotes: 1

Related Questions