如何用关联编写范围?

时间:2012-11-25 22:14:15

标签: ruby-on-rails ruby-on-rails-3 scope

你能帮我写下面的范围:

Cv belongs_to Student我想写一个范围,它给了我所有cvs,其中学生至少有一个  教育(student.edcuations.any?)和学生有效(填写所有属性)

我想为Cv编写该范围。

模型

#cv.rb
belongs_to :student

#student.rb
has_many :cvs
has_many :educations

2 个答案:

答案 0 :(得分:3)

我认为我误解了模型的布局。

我觉得它应该看起来更像这样,因为每个简历都会列出一个教育(否则,数据库中的相互连接如何)

#cv.rb
belongs_to :student
has_many :educations

#student.rb
has_many :cvs

#education.rb
belongs_to :cvs

我可能只是使用类方法。

#student.rb
def cvs_with_education
   self.cvs.reject {|cv| cv.educations.empty?}
end

答案 1 :(得分:0)

查看ActieRecord Query Interface Guide的第11.2.3节,了解如何加入嵌套关联。

这样的东西
scope :with_education, joins(:student => :educations).where("some conditions")

您可能希望定义:valid_student范围,然后在其中利用它。

相关问题