2012-05-02 11 views
8

Sto usando Mongoid per la mia app e ho un problema nell'impostare le relazioni corrette per utenti e iscrizioni.Mongoid: appartiene_ all'utente e ha_uno utente

Tutto quello che devo fare è fare una semplice relazione "ha uno e appartiene ad uno" per il modello UserSubscription.

class User 
    has_many :user_subscriptions 
end 

class UserSubscription 
    belongs_to :user 

    has_one :user # user2 to which user1 is subscribed 
    field :category, :String 
end 

Tutto quello che voglio fare è di avere un elenco di sottoscrizioni per ogni utente:

> user1.user_subscriptions # list of subscription objects 
> user1.user_subscriptions << UserSubscription.create(:user => user2, :category => 'Test') 
> user1.user_subscriptions.where(:user => user2).delete_all 

come implementare questa? Grazie per il tuo aiuto.

risposta

10

Il problema è che si hanno due relazioni con lo stesso nome e che è necessaria una relazione inversa per la relazione has_one :user. Si può sempre provare qualcosa di simile:

class User 
    include Mongoid::Document 

    has_many :subscriptions 
    has_many :subscribers, :class_name => "Subscription", :inverse_of => :subscriber 
end 

class Subscription 
    include Mongoid::Document 

    field :category 

    belongs_to :owner, :class_name => "User", :inverse_of => :subscriptions 
    belongs_to :subscriber, :class_name => "User", :inverse_of => :subscribers 
end 

allora si dovrebbe essere in grado di fare cose come:

> user1.create_subscription(:subscriber => user2, :category => "Test") 
> user1.subscriptions.where(:subscriber => user2).delete_all 
+1

Grazie! Funziona quando cambio has_many relazione su User class a: has_many: subscriptions,: class_name => "Subscription",: inverse_of =>: owner –