使用Rails Rails find_by_SQL

时间:2015-12-11 14:26:52

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

我使用find_by_sql方法搜索用户表中的用户。

是否可以在select语句中使用rails代码?

 User.find_by_sql ["SELECT DISTINCT
                    users.*
                  FROM
                    users
                  JOIN
                    clients_courses cc
                  ON
                    cc.client_id = users.client_id
                  LEFT JOIN
                    memberships m
                  ON
                    m.user_id = users.id AND m.course_id = cc.course_id
                  WHERE
                    cc.course_id = ?
                    AND
                    m.user_id IS NULL
                    AND
                    users.active = ?
                    AND
                    users.firstname LIKE ? or users.lastname LIKE ?
                    AND NOT IN ( RAILS CODE )", self.id, true, "#{search}%", "#{search}%"]
  end

我用RAILS CODE标记了位置

我想做点什么:

Membership.where(" course_id =?",self.id).users

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:1)

你可以这样做 -

    member_user_ids  = []
    Membership.where("course_id = ?", self.id).map{|membership| membership.users.map{|user| member_user_ids << user.id}}

    # you might want to put a uniq! on member_user_ids

    User.find_by_sql ["SELECT DISTINCT
                users.*
              FROM
                users
              JOIN
                clients_courses cc
              ON
                cc.client_id = users.client_id
              LEFT JOIN
                memberships m
              ON
                m.user_id = users.id AND m.course_id = cc.course_id
              WHERE
                cc.course_id = ?
                AND
                m.user_id IS NULL
                AND
                users.active = ?
                AND
                users.firstname LIKE ? or users.lastname LIKE ?
                AND users.id NOT IN ( #{member_user_ids.join(',')} )", self.id, true, "#{search}%", "#{search}%"]

您还可以查看link,它解释了如何在where子句中放置字符串数组。