find
- find(*args)
- 仅按照栏位id查找符合匹配值的记录
- 若没找到,返回 RecordNotFound
- id可以是:
- 具体某一个id,比如find(1);返回查找到的对象
Product.find(1) # returns the object for id = 1
- 同时查找多个id,比如find(1, 3);返回以一组数组形式呈现的查找到的对象
Product.find(1,3) # returns an array for objects with ids in (1, 3)
- 如果key是integer,查找输入时若使用字串,find会自动用 to_i 方法把字串转成integer进行查找
Product.find("1") # returns the object for id = 1
- 同时查找数组形式的某个id或多个id,比如find([1])、find([1,3,4])、;返回以一组数组形式呈现的查找到的对象
Product.find([1]) # returns an array for the object with id = 1
Product.find([1, 3, 4]) # returns an array for objects with ids in (1, 3, 4)
- 如果没找到,返回 RecordNotFound
find_by
- find_by(arg, *args)
- 查找并返回符合条件的第一条记录
- 按照指定栏位的指定值查找匹配的第一条记录,而不必像find一样仅限制在id栏位进行查找
- 若没找到,返回nil
-
按照某个栏位指定的值进行查找
比如:Product.find_by(title: "product1")
(1) 查找 栏位为title中值为"product1"的记录
(2) returns the object for product.title = "product1"
-
按照多个栏位指定的值进行查找
比如:Product.find_by(title: "product1", price: 500)
(1) 查找 栏位title中值为"product1" 而且 栏位price中值为500 的记录
(2) returns the object for product.title = "product1" && product.price = 500
-
如果没找到,返回nil
-
也可以写成 find_by_column(key),比如:
Product.find_by_title("product1")
Product.find_by_price(500)
Product.find_by_id(1)
-
如果key是integer,查找输入时若使用字串,find_by会自动用 to_i 方法把字串转成integer进行查找,比如:
Product.find_by_price("500")
Product.find_by(price: "500")
网友评论