简体   繁体   中英

Run a specific assignment process multiple times in Ruby

I have been trying to run a process where I take a specific product and run a method where I associated 74 additional unassociated tags to it:

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

Flipping the nest returns the number of times in the loop, but does not produce results (attaching the unassociated tags to the Product):

 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

Products have_many tags, and tags have_one product.

The method in place works find for associating single tags to a group of products. How can I built the times loop into the system?

It would actually be ideal if I could run a range (Product.where(id >= 194617 AND id <= 194638) ), but I need to solve the inner loop first.

Method derived from:

Product.all.each do |product|
    tag = Tag.unassociated.last
    tag.location = Warehouse.primary
    tag.trackable = product
    tag.save! 
end

I would use tap for such a 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 yields self (in this case the specific product) to the block and returns self afterward.

Okay, I solved both parts of this by calling the ids I needed as a range:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM