2017-10-21 50 views
0

J'ai un modèle Spree::Quotation comme suitActiveRecord belongs_to association renvoie nil

class Spree::Quotation < ActiveRecord::Base 

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

Ce modèle est le PaymentTerm

class PaymentTerm < ActiveRecord::Base 

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

c'est le contenu de payment_terms Table

development=# SELECT "payment_terms".* FROM "payment_terms"; 

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

maintenant quand Je fais Spree::Quotation.first.payment_term Je reçois le payment_ terme correctement

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",... > 

Mais quand je fais PaymentTerm.first.quotation, je reçois 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 

Pourquoi est-il pas de charger la citation? Merci d'avance

Répondre

0

Vous ne devez pas spécifier la condition dans l'association belongs_to comme table payment_terms a l'attribut service_id.

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