ruby copy a paperclip attachment from one model to another?

前端 未结 4 1337
Happy的楠姐
Happy的楠姐 2021-01-03 22:30

I have two models like this:-

Model 1 - card - contains a representation of data of interest for front page
attachment name = cardimage
Model 2 - user - c

相关标签:
4条回答
  • 2021-01-03 23:11
    old_avatar = model1.avatar;
    model2.avatar.create(attachment: old_avatar.attachment);
    model2.save;
    

    It worked for me.

    0 讨论(0)
  • 2021-01-03 23:14

    This should do the trick, you could use an after_create callback if the models are associated, if not I would recommend doing it in the controller action that creates the card.

    instance_of_model_one.cardimage = instance_of_model_two.avatar
    instance_of_model_one.save
    
    0 讨论(0)
  • 2021-01-03 23:16

    Suppose you have 2 models:

    • User
    • Player

    You have to copy profile_image from User with id = 1 to Player with id = 10. You can perform the following:

    user = User.find(1)
    player = Player.find(10)
    
    player.profile_image = user.profile_image
    player.save!
    

    Sometimes this might save the file but with a file size of 0 Bytes. In such cases try the following:

    user = User.find(1)
    player = Player.find(10)
    
    player.profile_image = user.profile_image.url
    player.save!
    

    This shall do the work!

    0 讨论(0)
  • 2021-01-03 23:17

    Ideally, the approach mentioned by @cih should work:

    instance_of_model_one.cardimage = instance_of_model_two.avatar
    instance_of_model_one.save
    

    But in my case, it was creating a blank file in S3. To resolve the issue, I tried the below approach and it worked:

    instance_of_model_one.cardimage = instance_of_model_two.avatar.url
    instance_of_model_one.save
    

    Passing the URL instead of the object in the 1st statement resolved the issue.

    0 讨论(0)
提交回复
热议问题