ActiveRecord not returning when searching on parent's children

≯℡__Kan透↙ 提交于 2019-12-25 04:45:27

问题


Would love to know what simple error it is that I'm making this time...

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 []>

Not understanding why the second statement isn't finding the plan..


回答1:


You missed the concept that in conditional sql, the arguments that follow the condition are replaced in place of ? not compared to. So, replace the double == with =.

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

or simply,

current_user.plans.where(status: nil)


来源:https://stackoverflow.com/questions/31658941/activerecord-not-returning-when-searching-on-parents-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!