新手问题 请教:为什么通过多态的方式使用 includes 报错?正确的写法是什么?

aijinsong · December 25, 2013 · Last by aijinsong replied at December 28, 2013 · 2891 hits
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 报错?正确的写法是什么?

:as => :party migration 里字段为: t.belongs_to :party, polymorphic: true 试试?

#1 楼 @ChanceDoor 非常感谢您的提示。稍后我会将可用方案给出。

#2 楼 @aijinsong 正确的写法如下。希望对大家有帮助。

class Party < ActiveRecord::Base

  belongs_to :party , :polymorphic => true
  has_many :parties_telecom_numbers

end

class Person < ActiveRecord::Base

  has_one :party, :as => :party, :dependent => :destroy
  has_many :parties_telecom_numbers, :as => :party
  has_many :telecom_numbers, :through => :parties_telecom_numbers

end

class Customer < ActiveRecord::Base

  has_one :party, :as => :party
  has_many :parties_telecom_numbers, :as => :party
  has_many :telecom_numbers, :through => :parties_telecom_numbers

end

class TelecomNumber < ActiveRecord::Base
end

class PartiesTelecomNumber < ActiveRecord::Base

  belongs_to :party , :polymorphic => true
  belongs_to :telecom_number

end

#3 楼 @aijinsong 为什么 Party 还要 belongs_to :party 呢? 我的理解是所有有 telecom_number 的 model 加上has_many :parties_telecom_numbers, :as => :party 就行了吧,只要class PartiesTelecomNumber指定了:party 为多态

而且我都是在 migration 里指定多态,会创建两个字段

#4 楼 @ChanceDoor 后续我会找时间继续和您探讨这个问题。

You need to Sign in before reply, if you don't have an account, please Sign up first.