6

के साथ सहयोग में शामिल होने के माध्यम से मैं रेल 3.0 के लिए रेल 3.0 ऐप को अपग्रेड करने का प्रयास कर रहा हूं। मैंने देखा व्यवहार में से एक यह है कि मॉडल के बीच संबंध काम करना बंद कर दिया।रेल 4 हैस_मनी: चुनिंदा

मान लें हम निम्नलिखित मॉडल:

class Student < ActiveRecord::Base 
    has_many :teacher_students 
    has_many :teachers, :through => :teacher_students, :select => 'teacher_students.met_with_parent, teachers.*' 

    # The Rails 4 syntax 
    has_many :teachers, -> { select('teacher_students.met_with_parent, teachers.*') }, :through => :teacher_students 

end 

class Teacher < ActiveRecord::Base 
    has_many :teacher_students 
    has_many :students, :through => :teacher_students, :select => 'teacher_students.met_with_parent, students.*' 
end 

class TeacherStudent < ActiveRecord::Base 
    belongs_to :teacher 
    belongs_to :student 
    # Boolean column called 'met_with_parent' 
end 

अब हम ऐसा करने में सक्षम हैं:

teacher = Teacher.first 
students = teacher.students 
students.each do |student| 
    student.met_with_parent  # Accessing this column which is part of the join table 
end 

इस रेल 3.0 के लिए काम किया है, लेकिन अब ऑन रेल्स 4.0 मैं Unknown column 'met_with_parent' in 'field list' हो रही है मैं रेल का मानना ​​है 4 स्मार्ट होने की कोशिश कर रहा है और पूरे दिए गए टेबल को लोड नहीं कर रहा है।

+0

क्या पुराने वाक्यविन्यास रेल 4.0 में काम करता है? – lurker

+0

@mbratch नहीं यह काम नहीं करता है। वही समस्या होती है। पुराने वाक्यविन्यास रेल 4 के साथ बहिष्करण संदेशों का एक गुच्छा लॉग होगा। – Bill

+0

यदि आप met_with_parent के रूप में teacher_students.met_with_parent का चयन करने का प्रयास करेंगे तो क्या होगा? – faron

उत्तर

3

मैं व्यक्तिगत रूप से, निम्नलिखित दृष्टिकोण की सिफारिश करेंगे स्कोप का उपयोग कर:

class Student < ActiveRecord::Base 
    has_many :teacher_students 
    has_many :teachers, :through => :teacher_students 
end 

class Teacher < ActiveRecord::Base 
    has_many :teacher_students 
    has_many :students, :through => :teacher_students 

    scope :met_with_parent, -> { joins(:teacher_students).where('teacher_students.met_with_student = ?', true) } 
end 

class TeacherStudent < ActiveRecord::Base 
    belongs_to :teacher 
    belongs_to :student 
end 

तो आप निम्न कर सकते हैं:

Teacher.first.students.met_with_parent 

यह आप आवश्यक होने रिश्ते और फिल्टर बनाए रखने के लिए अनुमति देता है।

+0

जहां ('teacher_students.met_with_student =?', सत्य) - उह। बस नहीं। आपको बस इतना ही चाहिए "कहाँ ('teacher_students.met_with_student')"। उसके अलावा अच्छा लग रहा है। –