Search code examples
ruby-on-railsactiverecordpaperclipmass-assignment

Adding many photos to a record. Can't mass-assign protected attributes:


I'm trying to add photos to my app using paperclip. A mug can have many photos.

When I try to save a new mug I get this error:

ActiveModel::MassAssignmentSecurity::Error in MugsController#create

Can't mass-assign protected attributes: mugphoto

Mug.rb

class Mug < ActiveRecord::Base
  attr_accessible :name, :mugphotos_attributes
  has_many :mugphotos
  accepts_nested_attributes_for :mugphotos, :allow_destroy => true
end

Mugphoto.rb

class Mugphoto < ActiveRecord::Base
  belongs_to :mug

  has_attached_file :mugphoto, 
    :styles => {  
      :thumb => "100x100#" }
end

mug new.html.erb

<%= form_for @mug, :html => { :multipart => true } do |f| %>

  <p>name: <br>
  <%= f.text_field :name %></p>

  <%= f.fields_for :mugphoto do |photo| %>
    <p>photo: <br>
    <%= photo.file_field :mugphoto %></p>
  <% end %>     

  <div class="button"><%= submit_tag %></div>
<% end %>

mugs_controller

class MugsController < ApplicationController

  def new
    @mug = Mug.new
  end

  def create
    @mug = Mug.create(params[:mug])
    if @mug.save
      flash[:notice] = 'Mug added'
      redirect_to mugs_path
    else
      render :action => :new
    end
  end
end

Solution

  • You need to add attr_accessible :mugphoto in Mugphoto.rb