Rails 嵌套形式:更新创建多条记录

Rails nested form: update creates multiple records

我有菜单模型和照片模型,其中菜单与照片有 has_many 关系。对于图片上传,我使用的是回形针。我能够构建一个 nested_form,在照片 table 中创建照片和其他属性。但是,当我更新时,记录在照片 table 中重复,并且不会上传在更新表单中选择的新照片。感谢您的帮助。

菜单模型

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

这是 strong_parametersnested_params 一起使用时非常常见的问题。 白名单 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