2015-09-22 84 views
1

我有菜單模型和照片模型,其中菜單has_many與照片的關係。對於圖片上傳,我使用回形針。我能夠構建一個nested_form,在照片表中創建照片和其他屬性。但是,當我更新時,記錄將被複制到照片表中,並且不會上載在更新表單中選擇的新照片。感謝你的幫助。Rails嵌套窗體:更新創建多個記錄

菜單模式

class Menu < ActiveRecord::Base 
    has_many :photos, :dependent => :destroy 
    accepts_nested_attributes_for :photos, reject_if: :all_blank, allow_destroy: true 
end 

照片模式

class Photo < ActiveRecord::Base 
    belongs_to :menu 
    has_attached_file :image, 
     :styles => { :thumb => "100x100#", :medium => "300x300#", :large => "600x400>" }, 
     :url => "/assets/menus/photos/images/:id/:style/:basename.:extension", 
     :path => "#{Rails.root}/public/assets/menus/photos/images/:id/:style/:basename.:extension" 
    validates_attachment :image, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] } 
end 

form.html.haml

= simple_form_for @menu do |f| 
    = f.simple_fields_for :photos do |photo| 
    = render 'photo_fields', f: photo 

_photo_field.html.haml

.nested-fields 
    = f.file_field :image 
    = f.input :main_flag, as: :hidden, input_html: { value: "true" } 
    = f.input :user_id, as: :hidden, input_html: { value: "1"} 

menus_controller.rb

class MenusController < ApplicationController 
    ... 
    def update 
    @menu = Menu.find(params[:id]) 

    if @menu.update(menu_params) 
     if params[:image] 
     @menu.photos.destroy 
     @menu.photos.build(menu_params) 
     end 
     flash[:success]= 'Menu was successfully updated' 
     redirect_to brand_menus_path(@menu.brand_id) 
    else 
     render 'index' 
    end 
    end 

    private 
    def menu_params 
    params.require(:menu).permit(:name, :price, :brand_id, :category_id, :description, 
     photos_attributes: [:user_id, :image, :main_flag]) 
    end 
+0

敞開的第一這個問題時,我已經注意到了 - '@ menu.photos.destroy',我必須說,這不僅將無法正常工作它會拋出異常。 –

+0

謝謝!我刪除了代碼,它工作正常。 – Kaku

回答

1

nested_params使用時,這是與strong_parameters非常普遍的問題。 白名單photos_attributes:id應該解決您的問題

def menu_params 
    params.require(:menu).permit(:name, :price, :brand_id, :category_id, :description, 
    photos_attributes: [ :id, :user_id, :image, :main_flag]) 
end 
+1

非常感謝!你拯救了我的一天。花了這麼多小時搞清楚...... – Kaku

相關問題