2015-11-09 63 views
1

我正在使用gem嵌套窗體https://github.com/ryanb/nested_form以創建一個包含多個圖片的平面。 平面模型有很多圖片。 形式看起來像這樣:嵌套窗體呈現未知屬性錯誤

<%= simple_nested_form_for @flat do |f| %> 
    <%= f.error_notification %> 

    <div class="form-inputs"> 
    <%= f.input :name %> 
    <%= f.fields_for :pictures do |pictures_form| %> 
     <%= pictures_form.file_field :image %> 
     <%= pictures_form.link_to_remove ('<i class="fa fa-trash"></i>').html_safe %> 
    <% end %> 
    <%= f.link_to_add ('<i class="fa fa-plus"></i>').html_safe, :pictures %> 
    </div> 
    <div class="form-actions"> 
    <%= f.button :submit %> 
    </div> 
<% end %> 

我控制器創建行動:

def create 
    @flat = Flat.new(flat_params) 
    authorize @flat 
    @flat.user = current_user 
    @flat.pictures.build 

    if @flat.save 
     redirect_to flat_path(@flat), notice: 'Flat was successfully created.' 
    else 
     render :new 
    end 
    end 

和我flat_params:

def flat_params 
     params.require(:flat).permit(:name, pictures_attributes: [:id, :image, :_destroy]) 
    end 

我總是得到以下錯誤: 未知屬性 '形象'爲圖片。

我用的圖片上傳寶石回形針這是我的表圖片看起來如何在我的架構:

create_table "pictures", force: :cascade do |t| 
    t.datetime "created_at",   null: false 
    t.datetime "updated_at",   null: false 
    t.string "image_file_name" 
    t.string "image_content_type" 
    t.integer "image_file_size" 
    t.datetime "image_updated_at" 
    t.integer "flat_id" 
    end 

問題是什麼?

回答

0

你爲什麼create方法?這是你唯一的保存

def new 
    @flat = Flat.new 
    @flat.pictures.build #-> pictures.build should be in the new method only 
    end 

    def create 
    @flat = Flat.new flat_params 
    @flat.user = current_user 

    authorize @flat 

    if @flat.save 
     redirect_to @flat, notice: 'Flat was successfully created.' 
    else 
     render :new 
    end 
    end 

除上述(pictures.build),你的代碼看起來不錯。

可能的另一個問題是,您尚未在Picture模型中包含回形針參考。您需要具備以下條件:

#app/models/picture.rb 
class Picture < ActiveRecord::Base 
    has_attached_file :image #-> + any styling options etc 
end 

從您提供的代碼中,我可以給出。