我有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)
后将其删除?
答案 0 :(得分:2)
未经测试!
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
答案 1 :(得分:0)
我使用以下代码来解决问题,但我认为有更好的方法来解决这个问题
# 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