ActiveRecord - "包括" &安培; "其中"使用其他属性获取Nil和Not Nil语句

时间:2015-09-01 18:02:58

标签: ruby-on-rails activerecord null include where

我希望使用' .includes()'来有效地获得结果。

我需要包含表来检索非零的记录。我需要在查询中保留包含:true

使用postgres。

角色有很多任务。

任务属于角色。

以下工作但从Roles表中获取错误的记录。

Task.includes(:role).where(included: true, roles: {doer: nil})

下一部分是我想要的IDEA ...... 但很明显,where子句" s"角色"值。

Task.includes(:role).where(
    included: true,
    roles: {
        doer != nil    #=> where 'doer' is not 'nil'
    })

我正在寻找一个有效的查询,这就是我做包含的原因。 我不知道如何在没有多个查询的情况下获得此信息。

如果你理解这个问题,但认为可以更好地要求更清楚,请告诉我。除非使用多个法规,否则我无法在任何地方找到任何线索。

3 个答案:

答案 0 :(得分:2)

如下:

Task.includes(:roles).where.not('roles.doer' => nil)

这是rails 4-and-up惯例,对于rails 3,它将类似于:

Task.includes(:roles).where("roles.doer IS NOT NULL")

并且您不需要包含的属性,可以将其从模型中移除以用于这些目的。

因为您似乎确实需要included(oops)

Task.includes(:roles).where('tasks.included' => true, 'roles.doer' => !nil)

Aaah ..我多么喜欢postgres ..当你要求效率时,我认为这会失败,但我会回复正确的结果。如果您对选项进行基准测试,这是正确的(我认为)但速度很慢。

Task.joins('LEFT OUTER JOIN "roles" ON roles.user_id = user_id').where("tasks.included IS true AND roles.doer IS NOT NULL")

答案 1 :(得分:2)

我希望尽可能避免使用字符串,因此我会使用以下内容:

res <- merge(df, do.call(rbind,mget(ls(pattern='^comb\\.\\d+'))), by.x=c('frames', 'LV.vel.fps'), by.y= c('frames', 'speed.fps'), all.x=TRUE) colnames(res)[4] <- 'final.name'

如果您已将Task.includes(:role).where(included: true).where.not(roles: { doer: nil })表格中的included列专门设置为tasks,则您还可以将NULL FALSE个电话压缩为一个电话,但这会仍然只启动一个查询:

where

就我个人而言,我希望看到这些内容稍微清理一下,只要这些调用很常见。类似的东西:

Task.includes(:role).where.not(included: false, roles: { doer: nil })

因此生成的代码更具可读性:

scope :with_doer, -> { includes(:role).where.not(roles: { doer: nil }) }

您显然可以将此模式扩展到Task.with_doer.where(included: true)位。

请注意,ActiveRecord查询会被构建,然后使用&#34; kicker&#34;来踢到数据库。在大多数情况下,Rails有点偷偷摸摸地通过included: true#inspect进行。因此,您不必担心需要将#to_a个来电压缩为一个电话。

答案 2 :(得分:0)

写这样的SQL语句?

Task.includes(:role).where(“included ='true'AND roles.doer NOT'nil'”)