运行 一个特定的赋值过程在 Ruby 中多次
Run a specific assignment process multiple times in Ruby
我一直在尝试 运行 一个过程,在这个过程中我使用特定的产品,运行 一个方法,在这个过程中我将 74 个额外的非关联标签关联到它:
Product.where(id:194617) do |product|
product.74.times do
tag = Tag.unassociated.last
tag.location = Warehouse.primary
tag.trackable = product
tag.save!
end
end
irb):43: syntax error, unexpected tINTEGER, expecting '('
product.74.times do
翻转嵌套returns循环次数,但不产生结果(将未关联的标签附加到产品):
74.times do
Product.where(id:194617) do |product|
rfid_tag = RFIDTag.unassociated.last
rfid_tag.location = Warehouse.primary
rfid_tag.trackable = product
rfid_tag.save!
end
end
产品 have_many
标签和标签 have_one
产品。
该方法适用于将单个标签与一组产品相关联。如何在系统中构建 times
循环?
如果我能运行一个范围(Product.where(id >= 194617 AND id <= 194638)
)实际上是最理想的,但我需要先解决内部循环。
方法源自:
Product.all.each do |product|
tag = Tag.unassociated.last
tag.location = Warehouse.primary
tag.trackable = product
tag.save!
end
我会用 tap
来表示 use-case:
Product.where(id:194617).first.tap do |product|
74.times do
tag = Tag.unassociated.last
tag.location = Warehouse.primary
tag.trackable = product
tag.save!
end
end
tap
产生 self
(在本例中为特定产品)块,然后 returns self
。
好的,我通过调用我需要的 id 作为范围解决了这两个部分:
Product.where(id:194617..194638).each do |product|
74.times do
tag = Tag.unassociated.last
tag.location = Warehouse.primary
tag.trackable = product
tag.save!
end
end
我一直在尝试 运行 一个过程,在这个过程中我使用特定的产品,运行 一个方法,在这个过程中我将 74 个额外的非关联标签关联到它:
Product.where(id:194617) do |product|
product.74.times do
tag = Tag.unassociated.last
tag.location = Warehouse.primary
tag.trackable = product
tag.save!
end
end
irb):43: syntax error, unexpected tINTEGER, expecting '('
product.74.times do
翻转嵌套returns循环次数,但不产生结果(将未关联的标签附加到产品):
74.times do
Product.where(id:194617) do |product|
rfid_tag = RFIDTag.unassociated.last
rfid_tag.location = Warehouse.primary
rfid_tag.trackable = product
rfid_tag.save!
end
end
产品 have_many
标签和标签 have_one
产品。
该方法适用于将单个标签与一组产品相关联。如何在系统中构建 times
循环?
如果我能运行一个范围(Product.where(id >= 194617 AND id <= 194638)
)实际上是最理想的,但我需要先解决内部循环。
方法源自:
Product.all.each do |product|
tag = Tag.unassociated.last
tag.location = Warehouse.primary
tag.trackable = product
tag.save!
end
我会用 tap
来表示 use-case:
Product.where(id:194617).first.tap do |product|
74.times do
tag = Tag.unassociated.last
tag.location = Warehouse.primary
tag.trackable = product
tag.save!
end
end
tap
产生 self
(在本例中为特定产品)块,然后 returns self
。
好的,我通过调用我需要的 id 作为范围解决了这两个部分:
Product.where(id:194617..194638).each do |product|
74.times do
tag = Tag.unassociated.last
tag.location = Warehouse.primary
tag.trackable = product
tag.save!
end
end