Duplicating a record that contains a carrierwave a

2019-09-11 05:40发布

问题:

Protocol has_many Images.

I am using local storage.

In a controller, I am copying @protocol to @ dest and I use:

  @protocol.images.each do |i|
    tmp=i.dup
    tmp.avatar = File.open(i.avatar.current_path)
    tmp.save!
    @dest.images << tmp        
  end

The line:

tmp.avatar = File.open(i.avatar.current_path)

Throws this error:
"can't convert nil into Integer"

Shell session looks like this:

>> i.avatar.current_path  
=>    "/Users/perry_mac/rails_projects/mymri/public/system/images/avatars/000/000/097/original/ruby.jpg"  
>> File.open(i.avatar.current_path)  
=> #  <File:/Users/perry_mac/rails_projects/mymri/public/system/images/avatars/000/000/097/original/ruby.jpg>  
>> tmp.avatar = File.open(i.avatar.current_path)  
!! #<TypeError: can't convert nil into Integer>  
>>  

What am I doing wrong? My goal is to duplicate the record and copy the associated image files. I am OK storing the duplicates.

回答1:

This works:

  @protocol.images.each do |i|
    tmp=Image.new
    tmp.avatar = File.open(i.avatar.current_path)
    tmp.description = i.description
    tmp.save
    @dest.images << tmp        
  end

But I'd rather not have to manually copy the other columns, like 'description' Not sure why it fails when I use tmp=i.dup .