2011-10-27 26 views
1

我有一個名爲UserPrice的模型,它有一個表單,您可以一次創建多個UserPrice's。我有這個叫:all_dates這是假設來更新我的UserPrice模式叫:purchase_date的另一date_select領域的虛擬屬性,但因爲它是不正確做的工作,我需要在這裏這種方法的詳細解釋,所以我可以得到它的工作:更新我的模型的新記錄的方法

def save_all_dates_to_user_prices 
if !self.all_dates.nil? 
self.user_prices.each {|up| up.purchase_date = self.all_dates if up.new_record?} 
end 
end 

我就開始了:

  1. 我定義的方法save_all_dates_to_user_prices發生在我UserPrice模型 before_save

  2. if !self.all_dates.nil?表示正在檢查UserPrice.all_dates屬性是否爲空或不存在(nil?)。

這是我迷路的地方;沒有在這條線是肯定的:

self.user_prices.each {|up| up.purchase_date = self.all_dates if up.new_record?} 
  • 包裝中每個UserPrice.user_prices?如果我試圖獲得一組新記錄,它不會看起來像這樣嗎?
  • 爲什麼用|up|,是self.user_prices.each代表什麼?
  • self.user_prices.each =什麼都裹在{}(散列)?

除了回答我上面提到的問題,有人可以填寫/更正關於此方法的詳細信息嗎?

謝謝,我是Rails和Ruby試圖學習的代碼。

回答

3

eachEnumerable類的一種方法,Array和Hash都實現該方法。它將塊作爲參數並將其應用於Enumerable的所有元素。所以,你問的是線轉換是這樣的:

每個爲user_prices,分配給all_dates如果purchase_date這是一個新的user_price

up就是指當前Enumerale元素的變量。

這是good explanation of closures in ruby

2

這是一種Ruby代碼笨重一點,所以這裏是它的一個分解,稍微改寫:

def save_all_dates_to_user_prices 
    # If all_dates is defined... 
    if (self.all_dates) 
    # ...then for each entry in user_prices hereby called 'up'... 
    self.user_prices.each do |up| 
     # ...check if this is a new record... 
     if (up.new_record?) 
     # ...and assign the purchase_date 
     up.purchase_date = self.all_dates 
     end 
    end 
    end 
end 

如果你熟悉JavaScript,然後x.each { |y| ... }在Ruby是類似於x.each(function(y) { ... })在JavaScript與jQuery。在這兩種情況下,垂直條內的變量代表該功能塊的參數。