2017-07-15 95 views
0

我試圖在rails 5中從頭開始進行身份驗證,並且我的用戶信息在輸入註冊表單時沒有被保存。我也收到此錯誤軌道:::加載ActiveModel ForbiddenAttributesError如何將我的用戶信息從註冊表單保存到數據庫?

@user = User.new(PARAMS [:用戶])

class User < ApplicationRecord 

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 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 



<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 %><br /> 
<%= f.password_field :password_confirmation %> 
</p> 
<p class="button"><%= f.submit %></p> 
<% end %> 



class UsersController < ApplicationController 
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 
end 


class Post < ApplicationRecord 
has_secure_password 
end 

回答

1

,如果你從頭開始創建請確保你有強大的參數聲明中的每個控制器,讓我解釋一下,你在User.new(user_params)裏面創建方法,user_params是我們通常放在類的底部的另一種方法,我們把方法def user_params,這個我們聲明允許的字段/數據可以傳遞給我們的模型,因爲你使用bcrypt寶石,我認爲該領域是相同的如下

其他信息大多數軌道用戶usi ng devise gem授權用戶

class UsersController < ApplicationController 

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

    private 

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

非常感謝!所以對於鐵軌來說很陌生,並試圖將我的頭包裹在它周圍。 –

+0

如果它幫助和糾正你的問題,你可以通過檢查我的答案旁邊的標記來接受我的答案,所以這個問題標記爲已解決 – widjajayd

+0

這有幫助,但我也需要刪除attr_accessor。再次感謝:) –

相關問題