Rails活动记录重复并保存失败

时间:2015-07-13 15:54:17

标签: ruby-on-rails carrierwave

我有这个错误:Errno::ENOENT in PicturethingsController#update_profile

No such file or directory - /Users/Baz/rails/myapp/public/uploads/picturething/picture/49/cat.jpg

我正在尝试复制标准图片记录并将其保存到@ character.profilepicture。我也无法将@ character.profilepicture保存到数据库中(我知道在进入rails控制台后检查)。

这是令人讨厌的方法:

picturethings_controller.rb:

def update_profile
  @character = Character.find_by(callsign: params[:callsign])
  standardpicture = Picturething.find_by(id: params[:picid])
  @character.build_profilepicture
  @character.profilepicture.save!
  @character.profilepicture = standardpicture.dup
  @character.profilepicture.save!
  @character.profilepicture.picture.recreate_versions!
  @character.profilepicture.picture = @character.profilepicture.picture.profile
  respond_to do |format|
    format.html do
      redirect_to @character.sociable
    end
    format.js
  end
end

character.rb:

has_many :standardpictures, class_name: "Picturething",
                            inverse_of: :character,
                            foreign_key: "character_standard_id",
                            dependent: :destroy
has_one  :profilepicture,   class_name: "Picturething",
                            inverse_of: :character,
                            foreign_key: "character_profile_id",
                            dependent: :destroy

picturething.rb:

mount_uploader :picture, CharacterpicUploader

1 个答案:

答案 0 :(得分:6)

@character.profilepicture = standardpicture.dup

这个问题是它只复制ActiveRecord对象的属性,但它不会复制磁盘上的实际图片,所以当你这样做时

@character.profilepicture.picture = @character.profilepicture.picture.profile

它会引发No such file or directory错误。尝试使用this gem帮助您在AR记录之间复制CarrierWave附件。