Pergunta

I have spent a while trying and searching for answers to debug this.

I am following Railscast 250 (Authentication from scratch) which is intended for Rails 3 on Rails 4. Obviously there is a problem of strong parameters which I think I have solved using the usual method. I am currently getting this error:

undefined method `password' for #User:0xb640d880

Extracted source (around line #32): respond_to do |format|

 if @user.save
   format.html { redirect_to @user, notice: 'User was successfully created.' }
   format.json { render action: 'show', status: :created, location: @user }
 else

I know the controller can access the password attribute, but for some reason the model can't even though I am validating the presence of :password in the model.

user.rb

class User < ActiveRecord::Base
before_save :encrypt_password
validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates_presence_of :email
validates_uniqueness_of :email

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

users_controller.rb

class UsersController < ApplicationController
  before_action :set_user, only: [:show, :edit, :update, :destroy]

  # GET /users
  # GET /users.json
  def index
    @users = User.all
  end

  # GET /users/1
  # GET /users/1.json
  def show
  end

  # GET /users/new
  def new
    @user = User.new
  end

  # GET /users/1/edit
  def edit
  end

  # POST /users
  # POST /users.json
  def create
    logger.warn user_params[:password]
    @user = User.new(email: user_params[:email], password_hash: user_params[:password_hash], password_salt: user_params[:password_salt])

respond_to do |format|
  if @user.save
    format.html { redirect_to @user, notice: 'User was successfully created.' }
    format.json { render action: 'show', status: :created, location: @user }
  else
    format.html { render action: 'new' }
    format.json { render json: @user.errors, status: :unprocessable_entity }
  end
end
  end

  # PATCH/PUT /users/1
  # PATCH/PUT /users/1.json
  def update
        respond_to do |format|
          if @user.update(user_params)
           format.html { redirect_to @user, notice: 'User was successfully updated.' }
            format.json { head :no_content }
          else
            format.html { render action: 'edit' }
            format.json { render json: @user.errors, status: :unprocessable_entity }
          end
        end
  end

  # DELETE /users/1
  # DELETE /users/1.json
 def destroy
    @user.destroy
    respond_to do |format|
      format.html { redirect_to users_url }
      format.json { head :no_content }
    end
  end
  private

    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params.require(:user).permit(:email, :password_hash, :password_salt, :password)
    end
end

_form.html.erb (view)

<%= form_for(@user) do |f| %>
    <% if @user.errors.any? %>
      <div id="error_explanation">
        <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>

        <ul>
    <% @user.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
  </div>
<% end %>

<div class="field">
  <%= f.label :email %><br>
  <%= f.text_field :email %>
</div>
<div class="field">
  <%= f.label :password %><br>
  <%= f.password_field :password %>
</div>
<div class="field">
  <%= f.label :password %><br>
  <%= f.password_field :password %>
</div>
<div class="actions">
  <%= f.submit %>
</div>
  <% end %>

Thanks for your help!

Foi útil?

Solução

I have created an sample project of user authentication so please check it.

Users_controller.rb

class UsersController < ApplicationController

  def new
    @user = User.new
  end

  def create

    @user = User.new(user_params)
    #raise params.inspect
    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_hash, :password_salt, :password)
  end

end

new.html.erb

<h1>Sign Up</h1>

<%= form_for @user do |f| %>
  <% if @user.errors.any? %>
    <div class="error_messages">
      <h2>Form is invalid</h2>
      <ul>
        <% for message in @user.errors.full_messages %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
  <p>
    <%= f.label :email %><br />
    <%= f.text_field :email %>
  </p>
  <p>
    <%= f.label :password %><br />
    <%= f.password_field :password %>
  </p>
  <p>
    <%= f.label :password_confirmation %>
    <%= f.password_field :password_confirmation %>
  </p>
  <p class="button"><%= f.submit %></p>
<% end %>

user.rb

class User < ActiveRecord::Base
  attr_accessor :password
  before_save :encrypt_password


  validates_confirmation_of :password
  #validates_presence_of :password, :on => :create
  validates_presence_of :email
  validates_uniqueness_of :email

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

Above code is working properly.

Outras dicas

Your model is missing an attr_accessor for password. As you don't have a password column in your table but still need to receive the password attribute (so you can process it with a salt and then turn it into a hash), you need to have this accessor.

Add this in your user model:

attr_accessor :password

EDIT: Just like Amit Sharma pointed out in his demo.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top