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

时间:2016-02-11 05:38:37

标签: ruby-on-rails

`当我在视图表单中输入所有详细信息时,在提交表单时我收到此错误。

这是我的控制器: 控制器/ user_new_controller.rb

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

    def create_user

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


        # @user.update_attributes(params[:user], permit[:user_attribute]
        if @user.save
            flash[:notice] = "You signed up successfully"
            flash[:color] = "valid"

        else
            flash[:notice] = "Form is invalid"
            flash[:color] = "invalid"
        end
        render "new"

    end
    def applicationview

    end

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

这是我的模特:     模型/ user.rb

class User < ActiveRecord::Base

    before_save :encrypt_password
    after_save :clear_password

    def encrypt_password
        if password.present?
            salt = BCrypt::Engine.generate_salt
            encrypted_password = BCrypt::Engine.hash_secret(password, salt)
        end
    end

    def clear_password
        self.password = nil
    end

    attr_accessor :username, :email, :password, :password_confirmation
    # attr_accessor :user_attribute, :as => admin
    # attr_accessor :password
    # EMAIL_REGEX = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i
    # email_regexp = /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i
    validates :username, :presence => true, :uniqueness => true, :length => { :in => 3..20 }
    validates :email, :presence => true, :uniqueness => true 
        validates :password, :confirmation => true 
    validates_length_of :password, :in => 6..20, :on => :create
end

这是我的观点: views / applicationview.html.erb

    <% @page_title = "UserAuth | Signup" %>

<div class = "Sign_Form">
    <h2>Sign Up</h2>
    <%= form_for(:user, :url => {:controller => 'user_new', :action => 'create_user'}) do |f| %>
    <p> Username </br> <%= f.text_field :username%> </p>
    <p> Email </br> <%= f.text_field :email%> </p>
    <p> Password </br><%= f.text_field :Password %> </p>
    <p> Password_confirmation </br> <%= f.text_field :Password_confirmation%> </p>
    <%= f.submit :Signup %>
    <% end %>
</div>

我收到了图片中显示的以下错误 我收到ActiveModel错误。

我实际上正在查看我在视图中输入的详细信息,而我在渲染时会得到以下答案,

{ "username": "jack", "email": "jack@yahoo.com" }

我无法获取密码,这些值未存储在我的数据库中。在我的日志中,我收到了Unpermitted参数:Password,Password_confirmation这个动作正在发生。

1 个答案:

答案 0 :(得分:6)

您需要更改:

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

要:

@user = User.new(user_params)

这是因为Strong Parameters