2011-09-26 15 views
0

查詢返回基於使用限制()或第一不同的對象類型AR查詢返回的關係,而不是

此示例使用限制(1),並且不產生預期的對象類型的預期對象類型(模型人) :

c = PersonCategory.where("category = ?", "Crown").limit(1) ## 
=> PersonCategory Load (0.3ms) SELECT `person_categories`.* FROM `person_categories` WHERE (category = 'Crown') LIMIT 1 
=> [#<PersonCategory id: 1, category: "Crown">] ##### 
c.class 
=> ActiveRecord::Relation 

本例使用第一和得到所需的輸出:

c = PersonCategory.where("category = ?", "Crown").first ## 
=> PersonCategory Load (0.4ms) SELECT `person_categories`.* FROM `person_categories` WHERE (category = 'Crown') LIMIT 1 
=> #<PersonCategory id: 1, category: "Crown"> 
c.class 
=> PersonCategory(id: integer, category: string) ##### 
ruby-1.9.2-p180 :034 > 

回答

1

limit返回一組有限的結果。在你的情況下,即使你只指定一個對象爲limit(1),它也會返回基本上爲PersonCategory對象的數組。

例如,調用PersonCategory.limit(15)會返回數據庫中的前15個項目PersonCategory

first另一方面,只返回其前面查詢的第一個結果 - 而不是結果數組。這就是爲什麼你會看到個人返回對象PersonCategory

+0

當然!!!謝謝。 –

相關問題