Ruby on rails 更新我的模型的方法';世界新纪录
我有一个名为Ruby on rails 更新我的模型的方法';世界新纪录,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,我有一个名为UserPrice的模型,它有一个表单,您可以一次创建多个UserPrice。我有一个名为:all_dates的虚拟属性,它假设要更新我的UserPrice模型名为:purchase\u date的另一个日期选择字段,但由于它的工作不正确,我需要在此详细说明此方法,以便我可以让它工作: def save_all_dates_to_user_prices if !self.all_dates.nil? self.user_prices.each {|up| up.purchase_
UserPrice
的模型,它有一个表单,您可以一次创建多个UserPrice
。我有一个名为:all_dates
的虚拟属性,它假设要更新我的UserPrice
模型名为:purchase\u date
的另一个日期选择字段,但由于它的工作不正确,我需要在此详细说明此方法,以便我可以让它工作:
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
我将开始:
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\u价格?如果我试图获得一系列新记录,它不会是这样的,对吗李>
- 为什么要使用
,这是| up |
self.user\u价格。每个
代表什么
=包装在self.user\u prices.each
中的任何东西(散列){}
谢谢,我对Rails和Ruby还不熟悉,在编写代码的过程中尝试学习。
每个
都是类的一个方法,数组和哈希都实现了这个方法。它将块作为参数,并将其简单地应用于可枚举的所有元素。你问的那句话是这样翻译的:
对于每个用户价格
,如果是新的用户价格
up
只是一个引用当前枚举元素的变量
这里有一个。
每个
都是类的一个方法,数组和哈希都实现了这个方法。它将块作为参数,并将其简单地应用于可枚举的所有元素。你问的那句话是这样翻译的:
对于每个用户价格
,如果是新的用户价格
up
只是一个引用当前枚举元素的变量
这里有一个。这是一个有点笨重的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,那么Ruby中的
x.each{y}}
与使用jQuery的JavaScript中的x.each(function(y){…})
类似。在这两种情况下,竖条内的变量都表示该函数块的参数。这是一段有点笨重的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,那么Ruby中的x.each{y}}
与使用jQuery的JavaScript中的x.each(function(y){…})
类似。在这两种情况下,垂直条内的变量表示该函数块的参数