我想为一个小应用程序制作一个产品页面。此产品页面应允许用户添加多张照片。所以自然有三种模式。用户、产品和照片。用户 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
架构.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