2015-06-29 2 views
0

Я 3 модели userformation & achat(давайте переводить на свой род счетов).Уничтожить не разрушает

A user cand купить formation, он создаст achat. По причинам мне нужно удалить один achat. Но мне это не удалось. Я проверил следующий рабочий процесс, чтобы проверить мой код:

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 

Поэтому он не удаляется из базы данных. Как я должен уничтожить achat?


Вот (проще) версия моих моделей:

# 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 

Я через этот вопрос: dependent: :destroy doesn't work (has_many association), но это не помогло ...

+0

Вы пытались перезагрузить 'u'? 'u.reload' или' u.reload! '- это команда, в зависимости от вашей версии Rails. –

+0

Есть ли у вас обратный вызов? – Gerep

ответ

1

переменной Запись еще доступный даже уничтожен. Попробуйте

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

, чтобы убедиться, что вы удалили запись из базы данных

P.S. Рассмотрим destroyed? метод рельсов для понимания

+0

Хотя переменная доступна, длина не должна возвращаться 1, она должна быть обновлена ​​ – Gerep

+0

Нет. Вы видели запрос sql? Кажется, это значение кэшируется. – asiniy

0

Как указано в @ josh-burgess, вы можете уничтожить и затем перезагрузить объект.

u.achats.first.destroy! 
u.achats.reload 
Смежные вопросы