我在帖子/_form.html.haml 中有一个照片表单
看起来像这样:
.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
在编辑操作中,所有照片都使用正确的 post_id 保存。但是在创建 Post.new 时的创建操作中,它之前没有 id,所以照片没有得到 post_id。
不知何故这可以解决?也许删除这一行:
= f.input :post_id, val: @post.id, as: :hidden
并更改控制器以传递 id。
帖子控制器创建操作:
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