示例场景:模型 Workerbelongs_to
模型 Bucket。
请参阅以下查询:
1.9.3p194 :045 > Worker.where(bucket_id: Bucket.first).count
(0.7ms) SELECT COUNT(*) FROM "workers" WHERE "workers"."bucket_id" = 1
=> 38
1.9.3p194 :046 > Worker.where(bucket_id: Bucket.first.id).count
(0.7ms) SELECT COUNT(*) FROM "workers" WHERE "workers"."bucket_id" = 1
=> 38
1.9.3p194 :047 > Worker.new bucket_id: Bucket.first
=> #<Worker id: nil, email: nil, created_at: nil, updated_at: nil, bucket_id: nil>
1.9.3p194 :048 > Worker.new bucket_id: Bucket.first.id
=> #<Worker id: nil, email: nil, created_at: nil, updated_at: nil, bucket_id: 2>
正如您所看到的,在where
函数的情况下,传递一个实例,例如Bucket.first
作品来代替确切的id
. 所以有人会认为它也适用于该new
功能。相反,它默默地失败了!
为什么它会这样工作?