1

I've a piece of code in my product model where I assign values to columns by fetching from s3. The column names includes a counter "i" as well -

The 3 sample column names are -

pic1_file_name
pic2_file_name
pic3_file_name

The problematic code is -

  prod = Product.find(id)
  i=1
  s3 = AWS::S3.new
  bucket=s3.buckets['bucket_name']
       bucket.objects.each do |obj|
          prod.("pic"+"#{i}".to_s+"_file_name")=obj.key[45..1]
          # the above line give a syntax error, unexpected '=', expecting end-of-input
          prod.("pic"+"#{i}".to_s+"_file_name").to_sym   = obj.key[45..-1]
          # The above line gives an error undefined method `call' for #<Product:0x7773f18>
          prod.send("pic"+"#{i}".to_s+"_file_name")=obj.key[45..-1]
          # The above gives syntax error, unexpected '=', expecting end-of-input
          i+=1
       end
    prod.save

Could you please advise as to how should I structure my column name with a variable so that I can assign a value to it without having to type 15 separate columns every time.

Any pointers will be appreciated.

Thanks in advance!

1
  • Would suggest to pick either concatenation or string templating instead of mixing the two. Eg. "pic#{i}_file_name" or "pic" + i.to_s + "_file_name" Commented Aug 27, 2015 at 14:52

2 Answers 2

3

You almost got the last one right. You see, when doing

obj.pic1_file_name = 'foo'

you're actually calling method pic1_file_name=, not pic1_file_name. That line is equivalent to this:

obj.pic1_file_name=('foo')

With that in mind, your last line becomes

prod.send("pic#{i}_file_name=", obj.key[45..-1])
Sign up to request clarification or add additional context in comments.

Comments

2

You can use the send method to call a method from a string:

prod.send("pic#{i}_file_name") # to read

prod.send("pic#{i}_file_name=", obj.key[45..-1]) # to assign

2 Comments

Thanks you for the reply. I've tried this just now, but this gives me syntax error while opening the webpage itself. The error is in 'product.rb:148: syntax error, unexpected '=', expecting keyword_end prod.send("pic#{i}_file_name") = obj.key[45..-1] ^'
Sorry, that was to read the value, I edit the post to show assignment as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.