Question

My model constructor:

3.2:

  def initialize(attributes = {})
    super # must allow the active record to initialize!
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

4.0.4:

ActiveModel::ForbiddenAttributesError

How do I change the 3.2 constructor for 4.0.4 compatibility?

Was it helpful?

Solution

I guess you are getting this error when you try to create a new user from your User controller?

If you have code like:

class UsersController < ApplicationController
  ...
  def create
    @user = User.new(params[:user])
    ...
  end
  ...
end

Then this won't work because you can no longer do mass assignments in Rails 4.

Instead you need to whitelist the parameters in the controller something like this:

class UsersController < ApplicationController
  ...
  def create
    @user = User.new(user_params)
    ...
  end
  ...

  private

  def user_params
    params.require(:user).permit(:username, :password, :password_confirmation, :email)   # etc. according to your user model
  end
end

Having said this, I'm not sure why you need the constructor in your model at all? The initialize method you get from inheriting from ActiveRecord::Base should be enough. But in any event you will need to whitelist the parameters in your controller to avoid the ForbiddenAttributesError error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top