2013-08-30 136 views
0

我的職位/ _form.html.haml內的照片形式創建新的父模型模型PARENT_ID

是這樣的:

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

Posts控制器創建行動:

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 

回答

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" 

我希望這將有助於。