【发布时间】: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 NULL或IS 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