将ActiveRecord :: Relation转换为可用的数组

时间:2014-02-20 22:13:29

标签: ruby-on-rails ruby arrays activerecord

我打电话的时候:

preivous_lessons = @item.where("track_id = ?", lesson.track_id)

我得到了这个活跃的记录实现:

[#<CodeLesson id: 2, name: "Python", permalink: "python", lesson_content: "", instructions: "Print your name to the console.", hints: "", starting_code: "\"\"\"\r\nThis is a comment\r\n\"\"\"\r\n\r\nprint(\"Hello, World\"...", language_id: "12", order: 1, track_id: 2, user_id: 1, created_at: "2014-02-14 16:01:12", updated_at: "2014-02-15 21:14:43", visible: true>, #<CodeLesson id: 8, name: "Test Lesson", permalink: "test-lesson", lesson_content: nil, instructions: nil, hints: nil, starting_code: nil, language_id: "26", order: nil, track_id: 2, user_id: 1, created_at: "2014-02-20 19:23:15", updated_at: "2014-02-20 19:23:15", visible: false>]

如何将其转换为可用的模型数组,以便我可以执行以下操作:

preivous_lessons.each do |i|
  highest = i.order if i.order > highest
end

2 个答案:

答案 0 :(得分:1)

当OP从我的comment确认,我的提示解决了他的问题时,我把它作为帖子的答案:

preivous_lessons = @item.where("track_id = ?", lesson.track_id)
highest = preivous_lessons.maximum(:order)

maximum的文档:

  

计算给定列的最大值。返回的值与列的数据类型相同,如果没有行,则返回nil

答案 1 :(得分:0)

preivous_lessons = @item.where("track_id = ?", lesson.track_id).all