Mongoid 回形针照片在parent.update_attributes时被删除!(阿特尔)打电话



我有 2 个模型

User模型嵌入了许多pictures如下

class User
  include Mongoid::Document
  field :user_name, type: String
  embeds_many :pictures, cascade_callbacks: true
  ...
end

Picture模型实现如下

class Picture
  include Mongoid::Document
  include Mongoid::Paperclip
  field :description,   type: String
  has_mongoid_attached_file :photo,
  default_url: '',
  default_style: :thumb,
  url: "/:attachment/:id/:style.:extension",
  styles: {
    original: ['2000x1200>',  :jpg],
    thumb:    ['600x400#',    :jpg]
  },
  convert_options: {
    all: '-quality 90 -strip -background black -flatten +matte'
  }
  ...
end

问题出在user_controller#update

def update
   ...
   @user.update_attributes!(user_params)
   ...
end
def user_params
  params.require(:user).permit(:user_name, pictures:[:id, :description])
end

我希望这个#update能用id通过来更新图片的描述......确实如此。但是上传的图片在此更新后被删除?

如何更新上传照片的description而不会在使用@user.update_attributes!(user_params)后将其删除?

未测试!

pictures_params = params[:user].delete(:pictures)
@user.pictures.where(:id.in => pictures_params.map(&:id)).each do |pic|
  pic.set(:description, pictures_params.find{|p| p[:id] == pic.id}[:description])
end

我使用以下代码来解决问题,但我认为有更好的方法来解决这个问题

  # get the user hash to update both pictures and user
  user_params_hash = user_params
  # remove the picture from the hash to separate the updating of pictures from users
  picture_params_hash = user_params_hash.delete 'pictures'
  # update each picture description to avoid removing the photo
  unless picture_params_hash.nil?
    picture_params_hash.each do |picture_hash|
      picture = @user.pictures.find_or_create_by(id: picture_hash[:id])
      picture.description = picture_hash[:description]
      picture.save!
    end
  end
  # update the user attributes only without touching the embedded pictures
  @user.update_attributes!(user_params_hash)
end

最新更新