我的应用程序有交易模型和图片模型。我尝试使用fields_for标记用单一表单更新这两个模型,但是 交易模式仅更新(父模型),但不是图片模型。 我正在使用 carrierwave 进行图片上传。
Deal.rb
has_many :pictures,:dependent=> :destroy
accepts_nested_attributes_for :pictures, :reject_if => lambda {|a| a[:image].blank?}
end
Picture.rb
belongs_to :deal
mount_uploader :image, ImageUploader
deals_controller.rb
def new
@deal = Deal.new
@location = Location.find(params[:loc_id])
2.times{@deal.pictures.build}
end
def create
@location =Location.find(params[:loc_id])
@image
@deal = @location.deals.build(strong_params)
if @deal.save
redirect_to location_path(@location)
else
redirect_to root_url
end
end
private
def strong_params
params.require(:deal).permit(:deal_name,:category,:deal_type,picture_attributes:[:image])
end
new.html.erb
<h3>create new deal</h3>
<%=form_for @deal,:html=> {multipart: true} do |f|%>
<label>deal name</label>
<%=f.text_field :deal_name%>
<label>category</label>
<%=f.text_field :category%>
<label>type</label>
<%=f.text_field :deal_type%>
<%= hidden_field_tag(:loc_id, @location.id) %>
<%=f.fields_for :pictures do |builder|%>
<%=builder.file_field :image%>
<%end%>
<%=f.submit :submit%>
<%end%>
carrierwave 没有问题我通过在Deal模型中添加新的图片列来测试它。它工作正常。
我有什么遗漏。请帮助我。谢谢。
控制台日志
Parameters: {"utf8"=>"✓", "authenticity_token"=>"gw7iEC+Q4qX0X69yIoqBr/RyX5dAfePqXkBYhGWM1/C/SMugfWbYFoYzm/pQ2Rn3CzMkPtD3Vwqvr4bZjYcgGA==", "deal"=>{"deal_name"=>"stackover", "category"=>"dsfwerdsf", "deal_type"=>"sdfewer", "pictures_attributes"=>{"0"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007f1892c180c0 @tempfile=#<Tempfile:/tmp/RackMultipart20151021-12944-11d4ykd.png>, @original_filename="Screenshot from 2015-10-16 18:55:40.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"deal[pictures_attributes][0][image]\"; filename=\"Screenshot from 2015-10-16 18:55:40.png\"\r\nContent-Type: image/png\r\n">}, "1"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007f1892c67e68 @tempfile=#<Tempfile:/tmp/RackMultipart20151021-12944-1liyrcf.png>, @original_filename="Screenshot from 2015-09-28 15:55:20.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"deal[pictures_attributes][1][image]\"; filename=\"Screenshot from 2015-09-28 15:55:20.png\"\r\nContent-Type: image/png\r\n">}}}, "loc_id"=>"2", "commit"=>"submit"}
答案 0 :(得分:2)
错误在于你正在使用:
<%= f.fields_for :pictures do |builder| %>
<%= builder.file_field :image %>
<% end %>
请注意其复数形式为pictures
。
在白名单中,您允许picture_attributes
。
请改为尝试:
def strong_params
params.require(:deal)
.permit(
:deal_name,:category,:deal_type,
pictures_attributes:[:image]
)
end