我有菜单模型和照片模型,其中菜单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
敞开的第一这个问题时,我已经注意到了 - '@ menu.photos.destroy',我必须说,这不仅将无法正常工作它会抛出异常。 –
谢谢!我删除了代码,它工作正常。 – Kaku