问题
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