0

我在帖子/_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
4

1 回答 1

3

请试试这个

在新方法中使用这条线

  @post = Post.new
  @post.photos.build

假设如果你想要在编辑模式下的新照片意味着在编辑方法中使用这个

  @post.photos.build

在后期模型中,您必须使用

 has_may :photos
 accepts_nested_attributes_for :photos

在表单中更新代码如下

.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"   

我希望这会有所帮助。

于 2013-08-30T08:10:42.907 回答