【问题标题】:Is it possible to achieve 'or' in Active Record with an 'includes'?是否可以通过“包含”在 Active Record 中实现“或”?
【发布时间】:2014-04-26 00:42:16
【问题描述】:

我正在尝试从 ActiveRecord 模型中查询,我们称之为user

  • 用户has_many :projects
  • 项目has_one :thing
  • 用户has_many :things, through: :projects

我有兴趣找到所有具有thingscompleted 或根本没有thingsprojects

一些尝试:

projects.includes(:thing).where(
  things: { status: :complete }
).or(
  things: { id: nil }
)

projects.includes(:thing).where(
  things: [
    { status: :complete }, 
    { id: nil }
  ]
)

如果可能的话,我宁愿在没有 SQL 的情况下完成此任务,即使它是这样的:

query = projects.includes(:thing)
query.where(things: {id: nil}) & query.where(things: {status: :complete})

【问题讨论】:

  • 实际上,我想在结果中添加一个.order(:start_date),所以我不能使用&,因为这将返回一个数组,而不是一个活动记录关系。任何人都可以进行这个查询吗?
  • 我很想看看是否有办法通过部分 sql 查询来做到这一点。但仍然让 activerecord 来处理“包含”。
  • 如果您唯一的问题是订购,您可以先订购,然后映射。像 projects.order(:start_date).map 等等

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


【解决方案1】:

所以这可能适合你,也可能不适合你,但请尝试

query = projects.includes(:thing) query.where(things: {id: nil}).joins( query.where(things: {status: :complete}) )

我自己无法测试这个 atm,但我真的很好奇它是否真的会将这两个查询结合在一起。我稍后会玩它

【讨论】:

    猜你喜欢
    • 2012-02-28
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多