【问题标题】:Rails nested form: update creates multiple recordsRails 嵌套表单:更新创建多条记录
【发布时间】:2015-09-22 12:35:17
【问题描述】:

我有菜单模型和照片模型,其中菜单与照片有很多关系。对于图像上传,我使用的是回形针。我能够构建一个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

【问题讨论】:

  • 打开这个问题时我注意到的第一个 - @menu.photos.destroy,我必须说这不仅不起作用,还会引发异常。
  • 谢谢!我删除了代码,它工作正常。

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


【解决方案1】:

这是strong_parameters 与nested_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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多