2013-04-27 71 views
1

我目前正在調整fedena有很多:學生和監護人之間一對多的關係(而不是一個:許多學生:監護人)。如何找出通過多種活動記錄屬性許多

所以這是我做過什麼:

class Guardian < ActiveRecord::Base 
    has_many :parentings, :dependent=>:destroy 
    has_many :students, :through=>:parentings 
end 

class Student < ActiveRecord::Base 
    has_many :parentings, :dependent=>:destroy 
    has_many :guardians, :through=>:parentings 
end 

class Parenting < ActiveRecord::Base 
    attr_accessible :student_id, :guardian_id 
    belongs_to :student 
    belongs_to :guardian 
end 

guardian.rb有這個類方法:

def self.shift_user(student) 
    # find all the guardians having a ward_id = student.d (comment my own) 
    self.find_all_by_ward_id(student.id).each do |g| 
    .. 
end 

我想用新定義relationshop即

self.find_all_by_student_id(student.id).each do |g| 
.. 
改變它

它不起作用!我認爲它會工作,因爲我已經定義了一個守護者通過育兒類..我嘗試上述命令的幾個排列有很多同學和我不斷收到錯誤:

undefined method `find_all_by_student_id' for #<Class:0x1091c6b28> 

想法?我正在使用ruby 1.8.7RoR 2.3.5

回答

1

Guardian沒有propety student_id所以沒有方法find_all_by_student_id。所以我不明白你爲什麼感到困惑。你爲什麼不使用student.guardians

+0

哦..我想我沒有完全理解什麼活動記錄實際執行。我認爲它會自動將這些屬性添加到它包裹的對象中......但我想我錯了.. – abbood 2013-04-28 03:48:24

0

爲此,您可以使用一個名爲範圍和更復雜的查詢

class Guardian < ActiveRecord::Base 
    has_many :parentings, :dependent=>:destroy 
    has_many :students, :through=>:parentings 

    named_scope :find_all_by_student_id, lambda {|student_id| 
    { :all, 
     :select => "guardians.*", 
     :joins => "JOIN parentings ON parentings.guardian_id = guardians.id 
       JOIN students ON students.id = parentings.student_id", 
     :conditions = ["students.id = ?", student_id] } } 
end 
相關問題