Ruby

find 和 find_by

2017-10-07  本文已影响5人  Sarah_友妹

find


  1. 具体某一个id,比如find(1);返回查找到的对象
    Product.find(1) # returns the object for id = 1
  2. 同时查找多个id,比如find(1, 3);返回以一组数组形式呈现的查找到的对象
    Product.find(1,3) # returns an array for objects with ids in (1, 3)
  3. 如果key是integer,查找输入时若使用字串,find会自动用 to_i 方法把字串转成integer进行查找
    Product.find("1") # returns the object for id = 1
  4. 同时查找数组形式的某个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)
  5. 如果没找到,返回 RecordNotFound

find_by


  1. 按照某个栏位指定的值进行查找
    比如:Product.find_by(title: "product1")
    (1) 查找 栏位为title中值为"product1"的记录
    (2) returns the object for product.title = "product1"

  2. 按照多个栏位指定的值进行查找
    比如:Product.find_by(title: "product1", price: 500)
    (1) 查找 栏位title中值为"product1" 而且 栏位price中值为500 的记录
    (2) returns the object for product.title = "product1" && product.price = 500

  3. 如果没找到,返回nil

  4. 也可以写成 find_by_column(key),比如:
    Product.find_by_title("product1")
    Product.find_by_price(500)
    Product.find_by_id(1)

  5. 如果key是integer,查找输入时若使用字串,find_by会自动用 to_i 方法把字串转成integer进行查找,比如:
    Product.find_by_price("500")
    Product.find_by(price: "500")

上一篇 下一篇

猜你喜欢

热点阅读