class Party < ActiveRecord::Base
has_many :parties_telecom_numbers
end
class Customer < ActiveRecord::Base
has_many :parties_telecom_numbers, :as => Party
has_many :telecom_numbers, :through => :parties_telecom_numbers
end
class PartiesTelecomNumber < ActiveRecord::Base
belongs_to :party
belongs_to :telecom_number
end
class TelecomNumber < ActiveRecord::Base
end
class McCustomerQuery < ActiveRecord::Base
def self.findByTelecomNumber(telecomNumber)
#test1 result success
parties = Party.includes(:parties_telecom_numbers).limit(10)
parties.each { |partiy| puts partiy.parties_telecom_numbers.size }
#test2 result success
customers = Customer.all
customers.each { |customer| puts customer.parties_telecom_numbers.size }
#test3 result success
customers = Customer.all
customers.each { |customer| puts customer.telecom_numbers.size }
#test4 result fail
# NoMethodError (undefined method `each' for nil:NilClass):
# app/models/mc_customer_query.rb:20:in `findByTelecomNumber'
# app/controllers/parties_controller.rb:9:in `index'
customers = Customer.includes(:parties_telecom_numbers).limit(10)
customers.each { |customer| puts customer.parties_telecom_numbers.size }
end
end
请教:为什么通过多态的方式使用 includes 报错?正确的写法是什么?