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

我想使用新定义的关系商店来改变它,即

self.find_all_by_student_id(student.id).each do |g|
..

它不起作用!我认为它会起作用,因为我已经通过 Parenting 课程定义了 Guardian 有很多学生。我尝试了上述命令的几种排列,但我不断收到错误:

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

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

4

2 回答 2

1

Guardian has no propety student_id so there is no method find_all_by_student_id. So I don't understand why you are confused. Why don't you just use student.guardians?

于 2013-04-27T14:33:21.110 回答
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
于 2013-04-27T15:48:24.007 回答