ActiveRecord belongs_to association返回nil

时间:2017-10-21 02:44:48

标签: ruby-on-rails ruby activerecord

我的模型Spree::Quotation如下

class Spree::Quotation < ActiveRecord::Base

  has_one :payment_term, -> { where(service_type: 'Spree::Quotation') },
          class_name: 'PaymentTerm',
          foreign_key: 'service_id'
end

这是PaymentTerm型号

class PaymentTerm < ActiveRecord::Base

  belongs_to :quotation, -> { where(service_type: 'Spree::Quotation') },
             class_name: 'Spree::Quotation',
             primary_key: 'service_id'
end

这是payment_terms table

的内容
development=# SELECT "payment_terms".* FROM "payment_terms";

 id | service_id |   service_type   |     term     | 
----+------------+------------------+--------------+
  1 |          1 | Spree::Quotation | 100% upfront |
(1 row)

现在当我Spree::Quotation.first.payment_term时,我正确地收到了payment_term

2.1.8 :007 > Spree::Quotation.first.payment_term
  Spree::Quotation Load (1.0ms)  SELECT "spree_quotations".* FROM "spree_quotations" ORDER BY "spree_quotations"."id" ASC LIMIT 1
  PaymentTerm Load (0.7ms)  SELECT "payment_terms".* FROM "payment_terms" WHERE "payment_terms"."service_id" = $1 AND "payment_terms"."service_type" = 'Spree::Quotation' LIMIT 1  [["service_id", 1]]
 => #<PaymentTerm id: 1, service_id: 1, service_type: "Spree::Quotation", term: "100% upfront",... >

但当我PaymentTerm.first.quotation时,我正在nil

2.1.8 :008 > PaymentTerm.first.quotation
  PaymentTerm Load (0.8ms)  SELECT "payment_terms".* FROM "payment_terms" ORDER BY "payment_terms"."id" ASC LIMIT 1
 => nil

为什么不加载报价?提前致谢

1 个答案:

答案 0 :(得分:0)

您不必在belongs_to关联中指定条件,因为payment_terms表具有属性service_id

class PaymentTerm < ActiveRecord::Base
  belongs_to :quotation, class_name: 'Spree::Quotation', foreign_key: 'service_id'
end
相关问题