I have a model named UserPrice which has a form where you can create many UserPrice's at once. I have this virtual attribute called :all_dates which is suppose to update another date_select field of my UserPrice model called :purchase_date but since it isn’t doing its job correctly I need a detailed explanation on this method here so I can get it to work:
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
I’ll start out:
-
I defined the method
save_all_dates_to_user_pricesto happen
before_savein my UserPrice model. -
if !self.all_dates.nil?means the UserPrice.all_dates attribute is being check if it is blank or not there (nil?).
This is where I get lost; not being sure on this line:
self.user_prices.each {|up| up.purchase_date = self.all_dates if up.new_record?}
- Its wrapping each UserPrice.user_prices? It wouldn’t look like this if I am trying to get an Array of new records right?
- Why use
|up|, is that theself.user_prices.eachstands for? self.user_prices.each= anything wrapped in the{}(hashes)?
Along with answering the questions I have above could someone fill/correct the details for me about this method?
Thanks, I am new to Rails and Ruby trying to learn as I code.
eachis a method of the Enumerable class, which both Array and Hash implement. It takes a block as an argument and simply applies it to all the elements of the Enumerable. So the line you’re asking about translates like this:for each for the
user_prices, assignall_datestopurchase_dateif it’s a newuser_priceThe
upis just a variable referring to the current Enumerale element.Here’s a good explanation of closures in ruby.