Rails嵌套表单:update创建多个记录

时间:2015-09-22 12:35:17

标签: ruby-on-rails ruby-on-rails-4 paperclip nested-forms

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

菜单型号

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

1 个答案:

答案 0 :(得分:2)

strong_parametersnested_params一起使用时,这是一个非常常见的问题。 白名单 :id中的photos_attributes应解决您的问题

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