2012-06-22 35 views
0

我想通過where查詢定義一個新的數組,但我只能讓它工作一種方式。收集返回由於.where沒有如預期的響應

這就是:

<% 

@children = Array.new 
Topic.where(breadcrumb_id: @topic.id).each do |y| 
    @children.push(y.name) 
end 


return @children 
%> 


Returns the array ["Performance Arts", "Visual Arts", "Physical Arts", "Music", "Culinary Arts"] (All topics) 

但我寧願只是做

@children = Topic.where(breadcrumb_id: @topic.id) 

    return @children.each.name 

    Returns "undefined method `name' for #<Enumerator:0x007fe92205a1f0>" 

無論出於何種原因。每次將無法正確響應......雖然它適用於初次通話地方在第一個例子中。有什麼不同?

有沒有辦法做到這一點,以便我可以通過數組直接拉名稱?

回答

1

#where方法返回ActiveRecord::Relation對象,而不是數組。

要得到一個數組,調用#ALL或#to_a它:

@children = Topic.where(breadcrumb_id: @topic.id).all 
@children = Topic.where(breadcrumb_id: @topic.id).to_a 

注意,你並不需要將其轉換爲一個數組,以循環訪問它。

檢查出Frederick Cheung的答案,爲什麼你使用#each不起作用。

+0

謝謝一堆拉爾斯。我被困在此約2小時。 –

+0

您無法調用'Topic.where(breadcrumb_id:@ topic.id).to_a.name',這裏沒有ActiveRecord :: Relation的問題。 –

3

這只是each沒有的。你可能會尋找map(或別名),collect

Topic.where(...).map {|topic| topic.name} 

你可以說,使用符號#to_proc快捷短一點:

Topic.where(...).map &:name 
+0

我對這些都不太熟悉。我將不得不測試它們並閱讀它們。 –

2

On Rails的3.2有也pluck

@children = Topic.where(breadcrumb_id: @topic.id).pluck("name") 

這有額外的好處,做一個SELECT name FROM ...而不是SELECT *

+1

我忘了拔!它也看起來好像沒有實際實例化任何活動記錄對象,所以應該比'Topic.select('name')。map(&:name)' –

+0

稍微快一點並且使用更少的內存:) – Teoulas