与ActiveModel :: ForbiddenAttributesError的Rails注册表单问题

时间:2018-10-14 23:03:52

标签: ruby-on-rails

我正在尝试创建注册表单,但是参数很强。 您可以在http://www.blaz1988.webfactional.com/users/new

上尝试一下

这是users_controller.rb的代码

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

def create
  @user = User.new(params[:user])
  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 index
  @users = User.all  
end

private

def user_params
  params.require(:user).permit(:username, :email, :encrypted_password, 
  :salt)
end
end

我在user_params下添加了强大的参数,但是每当我尝试创建新用户时,UsersController#create中都会出现错误ActiveModel :: ForbiddenAttributesError

这是用户模型的代码

    class User < ApplicationRecord
      attr_accessor :password

      EMAIL_REGEX = /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\Z/i
      validates :username, :presence => true, :uniqueness => true, :length => { :in => 3..20 }
      validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
      validates :password, :confirmation => true #password_confirmation attr
      validates_length_of :password, :in => 6..20, :on => :create

      before_save :encrypt_password
        after_save :clear_password

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

        def clear_password
          self.password = nil
        end
    end

这是new.html.erb的代码

<% @page_title = "UserAuth | Signup" %>
<div class="Sign_Form">
  <h1>Sign Up</h1>
  <%= form_for(:user, :url => {:controller => 'users', :action => 'create'}) do |f| %>
    <p> Username:</br> <%= f.text_field :username%> </p>
    <p> Email:</br> <%= f.text_field :email%> </p>
    <p> Password:</br> <%= f.password_field :password%></p>
    <p> Password Confirmation:</br> <%= f.password_field :password_confirmation%> </p>
    <%= f.submit :Signup %>
  <% end %>
  <% if @user.errors.any? %>
    <ul class="Signup_Errors">
    <% for message_error in @user.errors.full_messages %>
      <li>* <%= message_error %></li>
    <% end %>
    </ul>
  <% end %>
</div>

如您所见,它是简单的注册表单,但是我无法解决具有强参数的问题。我试图用:password,:password_confirmation扩展user_parms,但仍然收到相同的错误消息。

它不是重复的,因为正如您所看到的,我使用了ActiveModel::ForbiddenAttributesError when creating new user中的解决方案,但仍无法正常工作。

0 个答案:

没有答案