我的模型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
为什么不加载报价?提前致谢
答案 0 :(得分:0)
您不必在belongs_to
关联中指定条件,因为payment_terms
表具有属性service_id
。
class PaymentTerm < ActiveRecord::Base
belongs_to :quotation, class_name: 'Spree::Quotation', foreign_key: 'service_id'
end