我是新来的。 我看到有很多方法可以找到记录:
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>).firstAnd 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.firstfind_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).
更多推荐
发布评论