find与find_by的区别

Published on:

find

根据id进行查询,像Product.find(3),查询语句是Product Load (0.1ms) SELECT "products".* FROM "products" WHERE "products"."id" = ? LIMIT ? [["id", 3], ["LIMIT", 1]],也可以直接传一个Product的对象,像

product = Product.first
Product.find(product)

find会把传过去的model对象的id进行查询。甚至可以这样:

user = User.last
Product.find(user)

find会把user的id的值进行查询。
find没有查询到结果,会抛出一个ActiveRecord::RecordNotFound异常。

find_by

需要传递一个hash作为参数。像Product.find_by(id:3),查询语句是Product Load (0.1ms) SELECT "products".* FROM "products" WHERE "products"."id" = ? LIMIT ? [["id", 3], ["LIMIT", 1]]。当然也可以查询其它的字段,像Product.find_by(title: 'the yellow book',查询语句是Product Load (0.1ms) SELECT "products".* FROM "products" WHERE "products"."title" = ? LIMIT ? [["title", "the yellow book"], ["LIMIT", 1]]
find_by没有查询到结果,会返回nil

where

where返回的是一个ActiveRecord_Relation集合,并不是一个model的对象,像product = Product.where("id = 1"),查询后,这样使用product.id是不行的,需要这样prodcut.first.id或者product.take.id

Comments

comments powered by Disqus