我有以下带有关联的类:
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
我能做到:
technician.tickets.service.price
但我做不到:
customer.orders.technician.name
customer.orders.last.tickets.technician.name
我如何从客户到技术人员或服务人员?
答案 0 :(得分:1)
问题是你无法在一组对象上调用属性。
customer.orders.technician.name
这里有一个orders
的集合。每个order
可以有不同的technician
。这就是为什么你不能在集合上调用technician
。
解决方案:在每个technician
对象上调用order
:
customer.orders.each do |order|
order.technician.name
end
第二个例子也是如此。而不是:
customer.orders.last.tickets.technician.name
使用:
customer.orders.last.tickets.each do |ticket|
ticket.technician.name
end