2011-03-16 13 views
9

मैं दो मॉडल, मद और उत्पाद मिल गया है के रूप में इस का उपयोग करते हुए:रेल: belongs_to और has_many अमानक आईडी

irb(main):007:0> Item 
=> Item(id: integer, identification_number: string, production_date: date, 
     created_at: datetime, updated_at: datetime, going_in: boolean) 
irb(main):008:0> Product 
=> Product(id: integer, sku: string, barcode_identification: string, 
      created_at: datetime, updated_at: datetime) 

में सोच एक आइटम एक विशेष उत्पाद की है।

मैं के माध्यम से

class Product < ActiveRecord::Base 
    has_many :items, :foreign_key => "identification_number", 
        :primary_key => "barcode_identification" 
end 

किसी विशेष उत्पाद के सभी आइटम्स (Product.find (1) .items) का उल्लेख करने में कामयाब रहे है लेकिन मैं किसी विशेष आइटम के उत्पाद उल्लेख करने के लिए नहीं लग सकता है। यह वही है मैं अब मिल गया है है:

class Item < ActiveRecord::Base 
    set_primary_key :identification_number 
    belongs_to :product, :foreign_key => "barcode_identification" 
end 

और जहाँ तक मेरी समझ फिर से के रूप में: डेटाबेस, चिंतित हैं कि काम करना चाहिए। सिवाय इसके कि यह नहीं है। शायद मैं यहाँ कुछ खो रहा हूँ? मैं रेल के लिए बिल्कुल नया हूं (लगभग एक महीने या उससे कम।)

उत्तर

15

यह एक belongs_to होने के लिए है? चूंकि आप प्राथमिक और विदेशी कुंजी दोनों निर्दिष्ट कर रहे हैं, क्यों नहीं

class Product < ActiveRecord::Base 
    has_many :items, :foreign_key => "identification_number", 
        :primary_key => "barcode_identification" 
end 

class Item < ActiveRecord::Base 
    has_one :product, :foreign_key => "barcode_identification", 
        :primary_key => "identification_number" 
end 
+1

क्या आप इस परिदृश्य के लिए हैस_ऑन काम करता है और संबंधित_ क्यों नहीं बता सकता है? मैं काम करने के लिए subs_to की उम्मीद करेंगे, लेकिन यह नहीं है। – ryanjones

+1

दिलचस्प। मेरे लिए काम किया धन्यवाद। अभी भी सोच रहा है कि क्यों संबंधित_to काम नहीं करता –

+0

@RonyVarghese 'belong_to' आइटम में काम करना चाहिए यदि आप विदेशी और प्राथमिक कुंजी सही तरीके से निर्दिष्ट करते हैं: ' belong_to: product,: foreign_key => "identification_number",: primary_key => "barcode_identification" (ध्यान दें कि चाबियाँ 'has_many' जैसी हैं!) सूक्ष्म भेद देखने के लिए इन दो विधियों के लिए दस्तावेज़ देखें: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_one और http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to – qix

1

आपके पास अपनी आइटम तालिका में एक विदेशी कुंजी होनी चाहिए। मुझे लगता है कि बारकोड_identification_id आइटम तालिका में एक कॉलम (विदेशी कुंजी) है। यदि आपके पास कुछ अन्य कॉलम है तो बस इसे इसके साथ बदलें।

इस तरह का प्रयास करें:

class Product < ActiveRecord::Base 
    set_primary_key :barcode_identification 
    has_many :items, :foreign_key => "barcode_identification_id" 
end 

class Item < ActiveRecord::Base 
    set_primary_key :identification_number 
    belongs_to :product 
end 
संबंधित मुद्दे