简体   繁体   中英

Ruby on Rails login form, always returns error can't be blank

I'm trying to setup a user sign-up system, and when I input an email and password, After pressing submit I always get the same errors: password can't be black, email can't be blank . I am a ruby newbie and have a hard time wrapping my head around parameters setting. If anyone can spot what I did wrong and point it out please do so. I would also be grateful for any documentation and explanations on what I did wrong.

I'm using rails 4.2.1 and ruby 2.2.1p85

Thanks

my controller:

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

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

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

my new.html.erb:

<h1>Sign Up</h1>

<%= form_for @user do |f| %>
    <%if @user.errors.any? %>
        <div class="error_messages">
            <h2>From 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 %><br />
        <%= f.password_field :password_confirmation %>
    </p>
    <p class="button"><%= f.submit %></p>   
<% end %>

my model(user.rb)

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

  validates_confirmation_of :password
  validates_presence_of :password
  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

You need to use user_params correctly. params[:user_params] will return nil .

Your create action should looks like:

def create
   @user = User.new(user_params)
   ...
   ...
end

params[:user_params]nil ,使用@user = User.new(user_params)代替

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM