2010-12-13 48 views
25

我覺得這是一個簡單的問題,由於我對新的ActiveRecord查詢接口的誤解,但以此爲例:Rails 3,Active Record查詢返回ActiveRecord :: Relation對象,而不是對象

>> Category.first.recipes 
=> [ ... ] # array of recipes 

但是:

>> Category.where(:id => 1).recipes 
=> NoMethodError: undefined method `recipes' for #<ActiveRecord::Relation:0x000001033dc9e0> 

這是怎麼回事嗎?爲什麼我的where方法返回一個ActiveRecord::Relation對象?我該如何從查詢中檢索對象?

回答

42

這其實是故意的。

Category.where(:id => 1) 
# Is Equivalent to Category.all(:conditions => {:id => 1}}) 
Category.where(:id => 1).first 
# Is equivalent of Category.first(:conditions => {:id => 1}}) 

只有在調用像first,each等特殊方法時纔會檢索對象。這被稱爲延遲加載,當你想緩存你的視圖時,這是一個很好的選擇。詳細瞭解爲什麼here

+4

投下來,因爲它不等效。 'where'返回ActiveRecord :: Relation,其餘返回Array或Model.class – 2010-12-26 12:20:02

+2

它在上下文中是等價的。這就是爲什麼我提到懶加載。但是,「.where.all」是等同的。 – Swanand 2010-12-27 05:02:55

6
Category.where(:id => 1).recipes 

返回一個數組。如果你只是做Category.where(:id => 1).first.recipes它應該工作。

3

但是,如果你只是在做一個違反id的地方,使用find方法 Category.find(1)將返回一個Category對象。
因此:
Category.find(1).recipes

相關問題