Ruby on rails 当parent.update\u属性时,Mongoid回形针照片将被删除!(attr)调用
我有两种型号Ruby on rails 当parent.update\u属性时,Mongoid回形针照片将被删除!(attr)调用,ruby-on-rails,mongoid,paperclip,Ruby On Rails,Mongoid,Paperclip,我有两种型号 用户模型嵌入了许多图片,如下所示 class User include Mongoid::Document field :user_name, type: String embeds_many :pictures, cascade_callbacks: true ... end class Picture include Mongoid::Document include Mongoid::Paperclip field :description,
用户
模型嵌入了许多图片
,如下所示
class User
include Mongoid::Document
field :user_name, type: String
embeds_many :pictures, cascade_callbacks: true
...
end
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
图片
模型实现如下
class User
include Mongoid::Document
field :user_name, type: String
embeds_many :pictures, cascade_callbacks: true
...
end
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\u 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
更新图片的描述。。。确实如此。
但此更新后上载的图片将被删除?
在使用@user.update\u属性后,如何更新上传照片的说明
!(用户参数)
?未测试
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
我也是这样做的。。。但难道没有更好的方法。。。或配置。。。这个代码看起来很臭,将来很难维护。。。为什么
update\u attributes
让嵌入的文档照片变得凌乱不堪。。。当它没有照片时?嵌入的集合是散列数组,所以当你说update\u attributes(:pictures=>…)
这意味着你改变了这个字段的值,意味着你改变了嵌入的集合,所以没有其他方法更新嵌入的文档?