2011-01-30 146 views
0

我正在嘗試構建包含許多組件的產品模型。有些組件是可選的,取決於用戶是否選擇啓用它們。 我有兩個模型,一個是配置,另一個是元素(該配置)。查找哈希數組中的元素

開始的時候我帶了數組的所有元素,然後創建另一個默認顯示的數組。 但是當我寫下面的代碼時,儘管兩個對象都是散列數組,但它給了我一個錯誤。

所以我把我的所有元素的第一陣列:

irb(main):252:0* @all = Configuration.find(1).elements 
=> [#<Element id: 1, name: "elem1", quantity: 1, position: 1, subposition: nil, created_at: nil, updated_at: nil, configuration_id: 1>, #<Element id: 2, name: "elem2", quantity: 2, position: 2, subposition: 1, created_at: nil, updated_at: nil, configuration_id: 1>, #<Element id: 3, name: "elem3", quantity: 3, position: 2, subposition: 2, created_at: nil, updated_at: nil, configuration_id: 1>, #<Element id: 4, name: "elem4", quantity: 4, position: 3, subposition: nil, created_at: nil, updated_at: nil, configuration_id: 1>] 

然後我過濾是隻有那些有subposition零或1

irb(main):253:0> @default = @all.where(:subposition=>nil).concat(@all.where(:subposition=>1)) 
=> [#<Element id: 1, name: "elem1", quantity: 1, position: 1, subposition: nil, created_at: nil, updated_at: nil, configuration_id: 1>, #<Element id: 4, name: "elem4", quantity: 4, position: 3, subposition: nil, created_at: nil, updated_at: nil, configuration_id: 1>, #<Element id: 2, name: "elem2", quantity: 2, position: 2, subposition: 1, created_at: nil, updated_at: nil, configuration_id: 1>] 

到目前爲止好,因爲你可以請參閱Elem3未在@default中顯示,因爲它不符合要求。

當我嘗試玩數組,因爲需要執行某些操作時,問題就出現了。

irb(main):257:0> @all.where(:position =>1) 
=> [#<Element id: 1, name: "elem1", quantity: 1, position: 1, subposition: nil, created_at: nil, updated_at: nil, configuration_id: 1>] 

但@default相同的操作將失敗,

irb(main):258:0> @default.where(:position =>1) 
NoMethodError: undefined method `where' for #<Array:0x2641660> 

現在,他們是哈希數組或看起來是一樣的,爲什麼同樣的方法在第二種情況下失敗?

非常感謝您的幫助!

回答

1

在整個代碼中,@allActiveRecord::Relation,而不是數組。這使您可以執行標準的.where呼叫(等等)。當您分配到@default時,您使用.concat來評估查詢並將實際數組分配給@default

您可能會在第二個代碼塊中嘗試不同的方法。也許像這樣:

@default = @all.where("subposition is null or subposition = ?", 1) 
0

那麼,你的問題是concat將一個集合轉換成一個數組。

我更換:

irb(main):253:0> @default = @all.where(:subposition=>nil).concat(@all.where(:subposition=>1)) 

由:

@default = @all.where("subposition = '1' OR subposition = nil") #I'm unsure of the nil in the statement, I nerver remember, try NULL if it fails 

這樣,你只作1分貝查詢和你保持一個ActiveRecord集合。

因此,您可以鏈接其他條件的地方。

相關問題