Active Record Rails 3 associations not working properly

徘徊边缘 提交于 2020-01-17 03:45:14

问题


I have the following classes with associations:

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  

I can do:
technician.tickets.service.price

But I can't do:
customer.orders.technician.name
customer.orders.last.tickets.technician.name

How do I go from customer to technician or service?


回答1:


The problem is that you cannot call a property on a collection of objects.

customer.orders.technician.name

Here you have a collection of orders. Each order could have a different technician. That's why you cannot call technician on a collection.

Solution: call technician on each order object:

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

Same goes for your second example. Instead of:

customer.orders.last.tickets.technician.name

Use:

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


来源:https://stackoverflow.com/questions/4003744/active-record-rails-3-associations-not-working-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!