找到vs find

编程入门 行业动态 更新时间:2024-10-25 04:16:32
找到vs find_by对于哪里(find vs find_by vs where)

我是新来的。 我看到有很多方法可以找到记录:

find_by_<columnname>(<columnvalue>) find(:first, :conditions => { <columnname> => <columnvalue> } where(<columnname> => <columnvalue>).first

而且看起来它们都是最终生成完全相同的SQL。 此外,我相信找到多个记录也是如此:

find_all_by_<columnname>(<columnvalue>) find(:all, :conditions => { <columnname> => <columnvalue> } where(<columnname> => <columnvalue>)

有没有一个使用的经验法则或建议?

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

find_by_<columnname>(<columnvalue>) find(:first, :conditions => { <columnname> => <columnvalue> } where(<columnname> => <columnvalue>).first

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:

find_all_by_<columnname>(<columnvalue>) find(:all, :conditions => { <columnname> => <columnvalue> } where(<columnname> => <columnvalue>)

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

最满意答案

使用最适合您最需要的人。

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

Model.find(1)

find其他用法通常被这样的东西所取代:

Model.all Model.first

当您在列中搜索信息时, Find_by用作帮助器,并将其映射到命名约定。 例如,如果您的数据库中有一个名为name的列,则可以使用以下语法:

Model.find_by_name("Bob")

不过,我相信find_by已被弃用。

.where更多的是捕捉到所有这些,让传统的帮助者不会使用更复杂的逻辑。

Use whichever one you feel suits your needs best.

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

Model.find(1)

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.

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

Model.all Model.first

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 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).

更多推荐

本文发布于:2023-08-06 03:19:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1443619.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:find

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!