【问题标题】:ActiveRecord not returning when searching on parent's children搜索父母的孩子时 ActiveRecord 不返回
【发布时间】:2015-07-27 16:55:31
【问题描述】:

很想知道这次我犯了什么简单的错误......

current_user = User.find(60)
Plan.joins(:user).where("users.id" => current_user.id).where("plans.status" => nil)
# Plan Load (8.6ms)  SELECT "plans".* FROM "plans" INNER JOIN "users" ON "users"."id" = "plans"."user_id" WHERE "users"."id" = 60 AND "plans"."status" IS NULL
# => #<ActiveRecord::Relation [#<Plan id: 54....]

current_user.plans.where("status == ?",nil)
# Plan Load (0.2ms)  SELECT "plans".* FROM "plans"  WHERE "plans"."user_id" = ? AND (status == NULL)  [["user_id", 60]]
# => #<ActiveRecord::AssociationRelation []>

不明白为什么第二个语句没有找到计划..

【问题讨论】:

  • users 表中是否也有状态列?
  • 不,这是我的第一个想法,但状态是计划独有的
  • 在 SQL 中,检查 NULL 是使用 IS NULLIS NOT NULL 完成的,因此您可以使用 current_user.plans.where('status IS NULL')。或者更好的是,current_user.plans.where(status: nil)current_user.plans.where(plans: { status: nil})

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


【解决方案1】:

您错过了在条件 sql 中,条件后面的参数被替换为 ? 而不是比较的概念。因此,将双 == 替换为 =

current_user.plans.where("status = ?",nil)

或者简单地说,

current_user.plans.where(status: nil)

【讨论】:

  • 您可以发布查询吗?我发现我的 ORM 没有任何问题。
  • 好吧,这是有道理的,但我很好奇,为什么这样做current_user.plans.where(status: nil) 会返回计划,但这样做:current_user.plans.where.not(status: "canceled") 不会?计划的状态为无或已取消
  • @james,阅读三值逻辑。 en.wikipedia.org/wiki/Three-valued_logic
猜你喜欢
  • 2018-07-12
  • 2020-05-26
  • 1970-01-01
  • 2012-08-29
  • 1970-01-01
  • 2016-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多