2013-03-12 92 views
0

我正在學習ruby,正在研究在ruby腳本中使用活動記錄的代碼庫..我不明白在puts命令後面的.collect語句中使用「&」:「 」。什麼樣的數據結構是Terminated_ids?Destroy_all方法使用混淆

destroy_all方法可以採用這種數據結構嗎?不知道用那個奇怪的&符號收集命令是什麼?

我想終止也使用destory_all的員工ID列表。但我的數據結構是像下面這樣的哈希:[{:emp_id=> "2637"},{:emp_id=> "2637"},{:emp_id=> "2637"},{:emp_id=> "2637"}]

請指教紅寶石noob ..謝謝!

class Maker < ActiveRecord::Base 
    host = 'superman.com' 
    port = 2000 
    sid = 'ASID' 

Maker.establish_connection(
    :adapter => 'oracle_enhanced', 
    :database => "someDB", 
    :username => 'user', 
    :password => 'passer' 
) 
    set_table_name 'WORK.EMPS' 
end 


puts 'removing terminated employees' 
Terminated_ids = Maker.where('term_date IS NOT NULL').collect(&:emp_id) # ??? 
OtherModel.destroy_all(:emp_id => Terminated_ids) 

puts 'removing employees who have been deleted' 
OtherModel.find_each do |othermodel| 
    if othermodel.email[-12,12] != '@ahsmsweh.com' #do not remove employees with an @ahsmsweh.com email 
    pbx_record = Maker.find_by_emp_id(othermodel.emp_id) 
    if pbx_record.nil? 
     puts "destroying missing record for #{othermodel.email}" 
     othermodel.destroy 
    end 
    end 
end 

回答

0

它是一條捷徑:

enumerable.collect(symbol.to_proc) 

其行爲一樣:

enumerable.collect {|element| element.send(symbol)} 

或者,在你的具體情況:

Maker.where('term_date IS NOT NULL').collect {|m| m.emp_id} 

其中產量的數組emp_id s(我假設在tegers)。

destroy_all傳遞包含:emp_id =>(整數數組)的地圖,它基本上搜索使用where然後對結果集調用destroy_all所有記錄:

where(:emp_id => [...]).destroy_all 

爲了您含有[{:emp_id=> "123"},{:emp_id=> "456"}, ...]哈希值的數組,那麼你可以使用同樣的方法來「崩潰」他們:

a = [{:emp_id=> "123"},{:emp_id=> "456"}, ...] 

OtherModel.destroy_all(:emp_id => a.map(&:values).(&:first)) 

當然,雖然可讀,我更喜歡更直接:

OtherModel.destroy_all(:emp_id => a.map {|h| h[:emp_id]}) 
+0

@Imtiaz Ahmad:請注意,@AlistairIsrael在本例中的map和collect是同一個方法的不同名稱。 – 2013-03-12 04:00:07