我正在使用 rails 3.2.11、mongoid 3.0.18、carrierwave (0.7.1) 和carrierwave-mongoid (0.3.0)
两种型号:产品有很多组件。组件有一个文件字段。我使用 gem nested_form 在产品页面上添加许多组件表单。
class Product
include Mongoid::Document
include Mongoid::Timestamps
field :title
field :image
embeds_many :components, cascade_callbacks: true
accepts_nested_attributes_for :components, allow_destroy: true
end
class Component
include Mongoid::Document
include Mongoid::Timestamps
field :title
field :author
field :file
embedded_in :product
mount_uploader :file, BaseFileUploader
end
控制器:
class ProductsController < BaseController
def update
resource = Product.find(params[:id])
if resource.update_attributes(params[:product])
redirect_to collection_path
else
resource.components.build unless resource.components # there should be always one component
render :edit
end
end
end
当我更改(!这个字段已经有值)只有一个文件字段时,没有保存查询到 db。
但是当我在控制器中添加强制保存时
class ProductsController < BaseController
def update
resource = Product.find(params[:id])
if resource.update_attributes(params[:product])
resource.components.each do |component|
component.save!
end
redirect_to collection_path
else
resource.components.build unless resource.components # there should be always one component
render :edit
end
end
end
它有效!你知道这里的原因是什么吗?