Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在每个记录的迭代过程中维护ActiveRecord查询的顺序_Ruby On Rails - Fatal编程技术网

Ruby on rails 在每个记录的迭代过程中维护ActiveRecord查询的顺序

Ruby on rails 在每个记录的迭代过程中维护ActiveRecord查询的顺序,ruby-on-rails,Ruby On Rails,我有以下关系: # == Schema Information # Table name: schools # id :integer not null, primary key # name :string(255) class School < ActiveRecord::Base has_many :teachers has_many :students, through: :teachers end # == Sche

我有以下关系:

# == Schema Information
# Table name: schools
#  id          :integer          not null, primary key
#  name        :string(255)
class School < ActiveRecord::Base
  has_many :teachers
  has_many :students, through: :teachers
end

# == Schema Information
# Table name: teachers
#  id          :integer          not null, primary key
# room_number  :integer 
class Teacher < ActiveRecord::Base
  belongs_to :school
  has_many :students
end

# == Schema Information
# Table name: students
#  id          :integer          not null, primary key
#  zip_code    :string(255)
class Student < ActiveRecord::Base
  belongs_to :school
  belongs_to :teacher
end
#==架构信息
#表名:学校
#id:整数不为空,主键
#名称:字符串(255)
班级学校
我想按教师的房间号和学生的邮政编码来排序结果。然后我需要遍历结果,并根据这个顺序将它们导出到csv

我可以很容易地得到订单:

class School < ActiveRecord::Base
  scope :order_by_room_number_and_zip_code, ->(id) { where(id: id).joins(teachers: :students).order('teachers.teachers asc, students.zip_code asc') }
end

School.order_by_room_number_and_zip_code(School.last)
班级学校(id){where(id:id).加入(教师::学生).排序('teachers.teachers asc,students.zip_code asc'))
结束
学校。按房间号和邮政编码订购(学校。最后)
问题是,当我遍历这些教师时,它们不再按照SQL生成的顺序排列

class School < ActiceRecord::Base
...
CSV.generate(options) do |csv|
   first.students.each do |student|
    csv << student.attributes.values_at(*(Student.column_names - Student.unneeded_column_names)) + student.teacher.attributes.values_at(*(Teacher.column_names - Teacher.unneeded_column_names))        
  end
end  
end
班级学校csv范围应该在教师模型中是的,通过学生迭代我最终使用了jvnill解决方案。但也可以使用pull:where(id:id).joins(a::b).order('a.column-asc,b.column-asc').pull(“a.column,b.column”)