0

I'm having trouble implementing strong parameters, receiving the Undefined Method attr_accessible error locally.

Could anyone explain what exactly I have done wrong here.

users_controller.rb:

class UsersController < ApplicationController
    def new
        @user = User.new
    end

    def create
        @user = User.new(user_params)
        if @user.save
            redirect_to root_url, :notice => "Signed up!"
            else
            render "new"
        end
    end

    def user_params
        params.require(:user).permit(:username, :email, :password, :password_confirmation)
    end
end

And in user.rb:

class User < ActiveRecord::Base
    attr_accessible :email, :password, :password_confirmation
    has_secure_password
    validates_presence_of :password, :on => :create
end

And perhaps a foolproof fix for this...I've tried a number of attempts but I just can't seem to get this right.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
GCien
  • 2,221
  • 6
  • 30
  • 56

2 Answers2

1

Rails 4 uses strong params by default, and you don't need attr_accessible. Also in rails 4 you permit params in the controller instead of the model.

How is attr_accessible used in Rails 4?

Community
  • 1
  • 1
Jesus Castello
  • 1,103
  • 11
  • 20
1

strong_params are usually done in the controller, not in the model. it's also described like this in the api. so, there's also no need for you to set attr_accesible. this way different controllers can also set different fields on a model, e.g. a backend users controller could be allowed to set an admin flag, while the users controller on the frontend is not allowed to do that.

so, your user_params method belongs in your UsersController, and the create and update action use user_params to filter out the params you don't allow to be set. e.g.:

@user = User.new(user_params)
srecnig
  • 898
  • 1
  • 7
  • 13