Search code examples
ruby-on-railsformsmass-assignment

update attributes cause mass assignment exception, even with attr_accessible


I receive the following error even though I have the fields to be updated in attr_accessible

Can't mass-assign protected attributes: utf8, _method, authenticity_token, profile, commit, action, controller, id

I'm guessing the other attributes that I don't want to save are raising the exception, but how can I filter them out?

this is the params hash

{"utf8"=>"✓",
 "_method"=>"put",
 "authenticity_token"=>"1aabj2DxleZoDu/U0SzGXSZrPcesRKXkIXTRVbk9f0A=",
 "profile"=>{"name"=>"Aaron Dufall",
 "company"=>"Supreme Windows",
 "location"=>"",
 "professional_bio"=>""},
 "commit"=>"Update",
 "id"=>"1"}

profiles_controller.rb

class ProfilesController < ApplicationController
    respond_to :html

    def edit
      @profile = Profile.find(params[:id])
      respond_with @profile
    end

    def update
        @profile = Profile.find(params[:id])
        if @profile.update_attributes(params)
           flash[:success] = "Profile sucessfully updated"
           redirect_to root_path
        else
           flash[:error] = "Profile failed to update"
           render 'edit'
        end
    end
end

profile.rb

class Profile < ActiveRecord::Base
  belongs_to :user
  attr_accessible :name, :company, :location, :professional_bio
end

Solution

  • In your controller you should use

    if @profile.update_attributes(params[:profile])
    

    This will filter only the attributes which are under "profile" key on params.