Rails - MassAssignmentSecurity ::多张照片上传时出错

时间:2013-06-05 16:32:54

标签: ruby-on-rails ruby ruby-on-rails-3

我想为一个小应用制作一个产品页面。此产品页面应允许用户添加多张照片。所以自然有三种模式。用户,产品和照片。用户has_many产品和产品has_many照片。

所有人都很花哨,但每当我尝试添加一些照片时,我都会收到此错误。

ActiveModel::MassAssignmentSecurity::Error in ProductsController#create

Can't mass-assign protected attributes: photos_attributes

产品控制器

  def new 
    @product = Product.new
    @photo = Photo.new
    4.times{ @product.photos.build }
  end

  def create
  @product = current_user.products.new(params[:product])
  @photo = current_user.photos.new(params[:photo])

    if @product.valid? && @photo.valid?
      @product.save
      @photo.product_id = @product.id
      @photo.save
        render "show", :notice => "Sale created!"
    else
        render "new", :notice => "Somehting went wrong!"
    end
  end

新产品页面(HAML)

= form_for @product,:url => products_path, :html => { :multipart => true } do |f|
  - if @product.errors.any?
    .error_messages
      %h2 Form is invalid
      %ul
        - for message in @product.errors.full_messages
          %li
            = message
  - if @photo.errors.any?
    .error_messages
      %h2 Image is invalid
      %ul
        - for message in @photo.errors.full_messages
          %li
            = message
  %p
    = f.label :name
    = f.text_field :name
  %p
    = f.label :description
    = f.text_field :description
  %p
    = f.fields_for :photos do |fp|
      =fp.file_field :image
      %br

  %p.button
    = f.submit

产品型号

class Product < ActiveRecord::Base
  attr_accessible :description, :name, :price, :condition, :ship_method, :ship_price, :quantity, :photo
  has_many :photos, dependent: :destroy
  accepts_nested_attributes_for :photos
  belongs_to :user
end

照片模型

class Photo < ActiveRecord::Base
  attr_accessible :image
  belongs_to :product
    has_attached_file :image, styles: { medium: "320x240>", :thumb => "100x100>"}
end

schema.rb

  create_table "photos", :force => true do |t|
    t.integer  "product_id"
    t.datetime "created_at",         :null => false
    t.datetime "updated_at",         :null => false
    t.string   "image_file_name"
    t.string   "image_content_type"
    t.integer  "image_file_size"
  end

  create_table "products", :force => true do |t|
    t.string   "name"
    t.text     "description"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
    t.integer  "user_id"
  end

编辑:当我添加:photos_attributes到产品型号attr_accessible我得到一个错误,上面写着图片不能为空!

1 个答案:

答案 0 :(得分:4)

只需将photos_attributes添加到产品型号的attr_accessible列表中即可。或者甚至更好,尝试迁移到strong_parameters gem,在迁移到Rails 4时会为您节省一些时间。

<强>更新

create操作中,您可以从@photo创建一个params[:photo]变量,该变量知道返回nil,导致该对象始终无效。也就是说,您不需要创建该变量,因为已经为Photo使用了accepts_nested_attributes_for对象。我了解您需要知道Photo是否已成功创建,但您不应该担心它,因为产品新照片中的错误会传播到产品,停止保存过程。