I have an application which have Deal model and Picture model.I tried to update these two models with single form using fields_for tag,but Deal model only getting updated(parent model) but not Picture model. I am using carrierwave for image upload.
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%>
There is no problem with carrierwave I tested it by adding a new image column to Deal model.It works fine.
Is there anything i am missing.Help me.Thanks in advance.
console log
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"}
The error is that you are using:
<%= f.fields_for :pictures do |builder| %>
<%= builder.file_field :image %>
<% end %>
Note that its pictures
in the plural.
While in your whitelist your are permitting picture_attributes
.
Try this instead:
def strong_params
params.require(:deal)
.permit(
:deal_name,:category,:deal_type,
pictures_attributes:[:image]
)
end