我有一个应用程序,其中有交易模型和图片模型。我试图更新这两个模型与单一的形式使用fields_for标签,但是交易模型只更新(父模型),而不更新图片模型。我使用载波进行图像上传。
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%>
载波没有问题,我通过向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"rnContent-Type: image/pngrn">}, "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"rnContent-Type: image/pngrn">}}}, "loc_id"=>"2", "commit"=>"submit"}
错误是您正在使用:
<%= 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