在我的rails应用程序中,我有两个模型学生和学生记录。
在student.rb中
has_many :student_records
accepts_nested_attributes_for :student_records, allow_destroy: true
现在,在我的一个模块中,我有一个检查范围唯一性的方法,我想传递一个有序版本的sibligs(student_records)。
validate :should_not_overlap
def should_not_overlap
@ranges = []
@counter = 0
student_records.order(date_from: :asc).each do |sr|
@ranges[@counter][sr.date_from] = sr.date_to
@counter += 1
end
if over_laps?(@ranges)
errors.add(:base, :should_not_overlap)
end
end
但订单不起作用。 over_laps?方法正在接收无序版本。发生了什么事?
答案 0 :(得分:2)
如果您的学生记录尚未保存,您可以尝试使用Array的方法#sort_by
:
student_records.sort_by(&:date_from)
我不确定ActiveRecord :: Relation是否在所有ActiveRecord版本中正确委派了该方法。确保您之前可以使用#to_a
:
student_records.to_a.sort_by(&:date_from)
但是,使用Rails 4.1时,这不是必需的。