【问题标题】:Convert ActiveRecord::Relation into a usable array将 ActiveRecord::Relation 转换为可用数组
【发布时间】:2014-02-20 22:13:28
【问题描述】:

当我打电话时:

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

【问题讨论】:

  • highest = preivous_lessons.map(&:order).max
  • highest = preivous_lessons.maximum(:order)
  • @ArupRakshit 然后我收到此错误comparison of NilClass with 1 failed
  • 你试过@item.where("track_id = ?", lesson.track_id).maximum(:order)吗?
  • 得到它的工作,错误是一个不相关的问题。 @ArupRakshit 发布并回答,我将选择它作为最佳答案。

标签: ruby-on-rails ruby arrays activerecord


【解决方案1】:

正如 OP 从我的 comment 确认的那样,我的提示解决了他的问题,我将其作为对帖子的回答:

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

maximum 的文档:

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

【讨论】:

    【解决方案2】:
    preivous_lessons = @item.where("track_id = ?", lesson.track_id).all
    

    【讨论】:

      猜你喜欢
      • 2013-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多