2010-10-23 8 views
0

je les classes suivantes avec les associations:actifs enregistrement Rails 3 associations ne fonctionnent pas correctement

class Customer < ActiveRecord::Base 
    has_many :orders 
    has_many :tickets, :through => :orders 
    has_many :technicians, :through => :ticket 
    has_many :services, :through => :ticket 
end 

class Order < ActiveRecord::Base 
    belongs_to :customer 
    has_many :tickets 
    has_many :technicians, :through => :tickets 
    has_many :services, :through => :tickets 
end 

class Service < ActiveRecord::Base 
    has_many :tickets 
    has_many :technicians, :through => :tickets 
    has_many :orders, :through => :tickets 
end 

class Technician < ActiveRecord::Base 
    has_many :tickets, :order => 'created_at DESC' 
    has_many :services, :through => :tickets 
    has_many :orders, :through => :tickets 
end 

class Ticket < ActiveRecord::Base 
    belongs_to :technician 
    belongs_to :service 
    belongs_to :order 
end 

je peux faire:
technician.tickets.service.price

Mais je ne peux pas le faire:
customer.orders.technician.name
customer.orders.last.tickets.technician.name

Comment puis-je aller de client à technicien ou service?

+0

Groovy/Grails peut le faire :-) Via le * -operator, qui diffuse un appel de méthode sur chaque élément dans une collection. Super chouette, avec aucune délégation via '?' La première chose que j'ai manqué en passant à Rails ... – Matthias

Répondre

1

Le problème est que vous ne pouvez pas appeler une propriété sur une collection d'objets.

customer.orders.technician.name 

Ici vous avez une collection de orders. Chaque order peut avoir un technician différent. C'est pourquoi vous ne pouvez pas appeler technician sur une collection.

Solution: appelez technician sur chaque objet order:

customer.orders.each do |order| 
    order.technician.name 
end 

va de même pour votre deuxième exemple. Au lieu de:

customer.orders.last.tickets.technician.name 

Utilisation:

customer.orders.last.tickets.each do |ticket| 
    ticket.technician.name 
end 
+0

merci beaucoup ... J'ai été bloqué sur cela pendant un certain temps –

+0

De rien. – Mischa

Questions connexes