Question

I created a project in Ruby On rails and I have controller user like this:

class UsersController < ApplicationController
    before_action :set_user, only: [:edit, :update]
    def new
        @user = User.new
    end

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

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

And model user like this:

class User < ActiveRecord::Base
  #attr_accessible :email, :password, :password_confirmation

  attr_accessor :password
  before_save :encrypt_password

  def self.authenticate(email, password)
    user = find_by_email(email)
    if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
      user
    else
      nil
    end
  end

  def encrypt_password
    if password.present?
      self.password_salt = BCrypt::Engine.generate_salt
      self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
    end
  end
end

And when I try to create new user i get Error: ActiveModel::ForbiddenAttributesError

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"74Mhbpn9FF/tY/cgfuVmX7ribN4rOkkdUjSgbLNsces=",
 "user"=>{"email"=>"henio180@interia.pl",
 "password"=>"[FILTERED]",
 "password_confirmation"=>"[FILTERED]"},
 "button"=>""}

I am using Ruby on Rails 4.0.3.

Was it helpful?

Solution

In your create method change:

@user = User.new(params[:user])

to

@user = User.new(user_params)

Although you created the method correctly to set up strong parameters, you are not actually using it. There is good detail about using strong parameters in the Rails guide: http://guides.rubyonrails.org/action_controller_overview.html#strong-parameters

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