【问题标题】:How to create active record query in rails?如何在 Rails 中创建活动记录查询?
【发布时间】:2022-07-26 22:17:21
【问题描述】:

我是 rails 新手,我有一个 sql 查询,但我不知道如何将其转换为 rails 活动记录查询。

UserExercise.connection.exec_query("SELECT * FROM (SELECT \"user_courses_progresses\".\"user_id\", \"user_courses_progresses\".\"progress\" FROM \"user_courses_progresses\" WHERE \"user_courses_progresses\".\"is_primary\" IS TRUE) x JOIN users ON \"x\".\"user_id\" = \"users\".\"id\" ORDER BY progress desc")

【问题讨论】:

    标签: sql ruby-on-rails postgresql activerecord


    【解决方案1】:

    结合 Active Record 和“原始”SQL,可能如下所示:

    User
      .select('*')
      .from(
        UserCoursesProgress
          .select(:user_id, :progress)
          .where(is_primary: true),
        :x
      )
      .joins('JOIN users ON x.user_id = users.id')
      .order(progress: :desc)
    

    【讨论】:

      猜你喜欢
      • 2013-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-07
      • 1970-01-01
      • 2020-02-28
      • 1970-01-01
      相关资源
      最近更新 更多