Reputation: 1276
I have a photos form inside the posts/_form.html.haml
Looks like this:
.row
.large-9.large-centered.columns
= simple_nested_form_for @post do |f|
= f.input :title, label: "Title"
= f.input :body, label: "Body", input_html: { rows: 15}
/= link_to_add_fields "Add image", f, :photos
= f.submit "Mentés", class: "button"
- if user_signed_in?
= simple_form_for @post.photos.new do |f|
%h3
Image upload
%i.fi-upload
= f.input :image, input_html: { multiple: true, name: "photo[image]"}, label: false
= f.input :post_id, val: @post.id, as: :hidden
On an edit action, all photos are saved with the correct post_id. But on a create action when Post.new gets created, it doesn't have an id before, so the photos don't get the post_id.
Somehow this could be fixed? Maybe deleting this line:
= f.input :post_id, val: @post.id, as: :hidden
and change the controller to pass the id.
Posts controller create action:
def create
@post = Post.new(post_params)
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render action: 'show', status: :created, location: @post }
else
format.html { render action: 'new' }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
Upvotes: 0
Views: 86
Reputation: 164
Please try with this
In new method use this line
@post = Post.new
@post.photos.build
Suppose if you want new photo in edit mode means In edit method use this
@post.photos.build
In post model you have to use
has_may :photos
accepts_nested_attributes_for :photos
In form update the code as below
.row
.large-9.large-centered.columns
= simple_nested_form_for @post do |f|
= f.input :title, label: "Title"
= f.input :body, label: "Body", input_html: { rows: 15}
/= link_to_add_fields "Add image", f, :photos
- if user_signed_in?
= f.fields_for :photos do |photo|
%h3
Image upload
%i.fi-upload
= photo.input :image, input_html: { multiple: true}, label: false
= f.submit "Mentés", class: "button"
I hope this will helps.
Upvotes: 3