find vs find_by vs where [英] find vs find_by vs where

查看:58
本文介绍了find vs find_by vs where的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Rails 的新手.我看到有很多方法可以找到记录:

I am new to rails. What I see that there are a lot of ways to find a record:

  1. find_by_()
  2. find(:first, :conditions => { => }
  3. where( => ).first

而且看起来它们最终都生成了完全相同的 SQL.另外,我相信查找多条记录也是如此:

And it looks like all of them end up generating exactly the same SQL. Also, I believe the same is true for finding multiple records:

  1. find_all_by_()
  2. find(:all, :conditions => { => }
  3. where( => )

是否有使用哪一个的经验法则或建议?

Is there a rule of thumb or recommendation on which one to use?

推荐答案

这个答案很旧,自从这篇文章发表以来,已经出现了其他更好的答案.我建议您查看@Hossam Khamis 在下面发布的帖子以了解更多详细信息.

This answer is very old and other, better answers have come up since this post was made. I'd advise looking at the one posted below by @Hossam Khamis for more details.

使用您认为最适合您需求的任何一种.

Use whichever one you feel suits your needs best.

find 方法通常用于通过 ID 检索一行:

The find method is usually used to retrieve a row by ID:

Model.find(1)

值得注意的是,如果您提供的属性没有找到该项目,find 将抛出异常.使用 where(如下所述,如果未找到该属性,它将返回一个空数组)以避免抛出异常.

It's worth noting that find will throw an exception if the item is not found by the attribute that you supply. Use where (as described below, which will return an empty array if the attribute is not found) to avoid an exception being thrown.

find 的其他用途通常被替换成这样:

Other uses of find are usually replaced with things like this:

Model.all
Model.first

find_by 用作在列中搜索信息时的帮助程序,它通过命名约定映射到此类.例如,如果您的数据库中有一个名为 name 的列,则应使用以下语法:

find_by is used as a helper when you're searching for information within a column, and it maps to such with naming conventions. For instance, if you have a column named name in your database, you'd use the following syntax:

Model.find_by(name: "Bob")

.where 更像是一个包罗万象的东西,它可以让您在传统助手无法执行的情况下使用更复杂的逻辑,并返回与您的条件匹配的项目数组(或否则为空数组).

.where is more of a catch all that lets you use a bit more complex logic for when the conventional helpers won't do, and it returns an array of items that match your conditions (or an empty array otherwise).

这篇关于find vs find_by vs where的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆