ActiveRecord中Find与Where区别

八 13th, 2011

find: 根据id查找,返回一个对象
find_by_*: 返回一个对象
find_all_by_*:返回Array
where: 返回ActiveRecord::Relation,操作对象时才执行SQL

在下面的示例中你可以清楚地比较各个语句的返回值和SQL

>> Bookmark.find(1)
SELECT "bookmarks".* FROM "bookmarks" WHERE "bookmarks"."id" = ? LIMIT 1  [["id", 1]]
#<Bookmark id: 1, name: "baidu", order: 0, url: "http://www.baidu.com">

>> Bookmark.find(1).class
SELECT "bookmarks".* FROM "bookmarks" WHERE "bookmarks"."id" = ? LIMIT 1  [["id", 1]]
Bookmark(id: integer, name: string, order: integer, url: string)

>> Bookmark.find_by_order(0).class
SELECT "bookmarks".* FROM "bookmarks" WHERE "bookmarks"."order" = 0 LIMIT 1
Bookmark(id: integer, name: string, order: integer, url: string)

>> Bookmark.find_all_by_order(0).class
SELECT "bookmarks".* FROM "bookmarks" WHERE "bookmarks"."order" = 0
Array

>> Bookmark.where(:order => 0).class
#不执行SQL
ActiveRecord::Relation

>> Bookmark.where(:order => 0)
SELECT "bookmarks".* FROM "bookmarks" WHERE "bookmarks"."order" = 0
[#<Bookmark id: 1, name: "baidu", order: 0, url: "http://www.baidu.com">,
 #<Bookmark id: 2, name: "rubyer", order: 0, url: "http://www.rubyer.me">]

>> Bookmark.where(:order => 0).first.class
SELECT "bookmarks".* FROM "bookmarks" WHERE "bookmarks"."order" = 0 LIMIT 1
Bookmark(id: integer, name: string, order: integer, url: string)
>>原创文章,欢迎转载。转载请注明:转载自Ruby迷,谢谢!
>>原文链接地址:ActiveRecord中Find与Where区别
目前还没有任何评论.