我正在调整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|
..
它不起作用!我认为它会起作用,因为我已经定义了一个Guardian通过Parenting类有很多学生..我已经尝试了上面命令的几个排列并且我继续得到错误:
undefined method `find_all_by_student_id' for #<Class:0x1091c6b28>
想法?我正在使用ruby 1.8.7
和RoR 2.3.5
答案 0 :(得分:1)
Guardian
没有属性student_id
,因此没有方法find_all_by_student_id
。所以我不明白为什么你感到困惑。你为什么不用student.guardians
?
答案 1 :(得分: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