Rails 4.2.0的Rails查询转换

时间:2015-05-08 08:00:41

标签: ruby-on-rails ruby ruby-on-rails-4

我从Rails 3.2.12升级到4.2.0

大多数事情现在都在运作,但一个查询是个问题。不知道如何将其转换为4.2.0

user_lesson = self.user_lessons.find :first,
              :include => [:lesson],
              :conditions => ["worked = ? AND passed = ?", true, false],
              :order => "lessons.sort"

我有第二个问题

memberships = Membership.find :all,
     :include => [:course],
     :conditions => ["next_mindmail < ? AND course_objects.active = ?", DateTime.now.utc, true]

我试过了:

memberships = Membership.joins(:course).where("next_mindmail < ? AND active = ?", DateTime.now.utc, true).all

但似乎不一样......

2 个答案:

答案 0 :(得分:1)

self.users.includes(:lesson).where("worked = ? AND passed = ?, true, fale).order('lessons.sort').first

所有rails查询接口都是here

答案 1 :(得分:1)

&#34; lesson.sort&#34;看起来它可以包含在关联中,如果它是您加入user_lessons和课程时应用的常见操作。即使它更为罕见,您也只能通过将其包含在关联中来获得对多个user_lessons的有效预先加载。

其他条件可能是范围,如果它们是共同条款。

这会让你有类似的东西:

user_lesson = self.user_lessons.
                join(:lesson_by_sort).
                where(worked: true, passed: false).
                first

或者也许:

user_lesson = self.user_lessons.
                failed.
                join(:lesson_by_sort).
                first

... user_lessons有:

def self.failed
  where(worked: true, passed: false)
end