使用`where`和`not in`的活动记录查询

时间:2015-04-24 22:46:58

标签: ruby-on-rails activerecord

我试图检索具有两个条件的所有用户。他们的profile_type必须是" Patient"而不是mod.vars

var mod = {
    "vars": [0, 1, 2]
};

mod.getArticles = function () {
    var results = [];
    var ids = this.vars;
    var request = function request(id) {
            return $.ajax({
                type: "GET",
                url: "/ajax/article/" + id + "/",
                // set `id` at `$.ajaxSettings` ,
                // available at returned `jqxhr` object
                id: id  
            })
            .then(function (data, textStatus, jqxhr) {
                // insert response `data` at `id` index within `results` array
                console.log(data); // `data` returned unordered
                // set `data` at `id` index within `results
                results[this.id] = data;
                return results[this.id]
            }, function (jqxhr, textStatus, errorThrown) {
                console.log("get article ajax error", errorThrown);
                return jqxhr
            });
    };

    return $.when.apply(this, $.map(ids, function (id) {
        return request(id)
    }))
    .then(function () {
        $.map(arguments, function (value, key) {
            if (value.length) {
                // append `value`:`data` returned by `$.ajax()`,
                // in order set by `mod.vars` items:`id` item at `request`
                mod.appendArticle(value);
            } else {
                console.error("get article ajax output error");
            };
        })
    });

};

mod.getArticles();

以下是有效的,但我希望它是一个查询而不是链。有很多例子只有blacklisted_idsblacklisted_ids = [1, 2, 3] User.where(profile_type: "Patient", id: not_in blacklisted_ids) ,但在单个查询中没有。

where

2 个答案:

答案 0 :(得分:0)

User.where('profile_type = ? AND id not in (?)', 'Patient', blacklisted_ids)

答案 1 :(得分:0)

链式标准是(在这种情况下)一个查询。它转换为一个sql语句。如果你想要的是在一个包装的where子句中语法表达它,那么你能做的最好就是

User.where("profile_type = 'Patient' and id not in (?)", blacklisted_ids)