2016-08-22 1 views
1

Je les modèles suivants dans mon schéma:validation a échoué en utilisant Cocoon pour polymorphes Association

class Notification < ApplicationRecord 
    has_many :impacts, as: :impactable 
    accepts_nested_attributes_for :impacts, reject_if: :all_blank, allow_destroy: true 
end 

class Impact < ApplicationRecord 
    #association 
    belongs_to :impactable, polymorphic: true 

    #enum 
    enum impact_type: [:full_school, :standard, :section] 
end 

Chaque fois que je tente de sauver une notification maintenant - j'obtenir l'erreur - Validation failed: Impacts impactable must exist

J'ai essayé pour créer des impacts à partir des notifications manuellement avec Notification.last.impacts.create et ils fonctionnent bien.

Quel pourrait être le problème ici?

Plus d'info - Lorsque j'ajoute un byebug à l'objet @notification avant qu'il enregistre dans le contrôleur - c'est la sortie -

>> @notification 
=> #<Notification id: nil, notification_type: "email", title: "Test", content: "Tomorrow is a holiday", created_at: nil, updated_at: nil> 

Et vérifier aussi pour ses associations -

>> @notification.impacts 
=> #<ActiveRecord::Associations::CollectionProxy [#<Impact id: nil, impact_type: "standard", standard: 2, created_at: nil, updated_at: nil, impactable_id: nil, impactable_type: "Notification", section: "">]> 

Répondre

2

Vous avez juste besoin d'ajouter inverse_of: :impactable à votre modèle de Notifications.

has_many :impacts, as: :impactable, inverse_of: :impactable