2013-04-29 59 views
0

這是我收到的例外:Rails的 - 菲爾茲從用戶的形式檢測到,但驗證仍然失敗

ActiveRecord::RecordInvalid in UsersController#create 
Validation failed: Email can't be blank, Password can't be blank 

但是,這些參數似乎正確地拾起:

請求

Parameters 

    {"utf8"=>"✓", 
    "authenticity_token"=>"l4gsQ/dO9+482Yf1Eq+MBSEVT9zcG4XdN37h1ZhnEIM=", 
    "user"=>{"email"=>"[email protected]", 
    "password"=>"[FILTERED]", 
    "password_confirmation"=>"[FILTERED]", 
    "username"=>"studentd", 
    "teacher"=>"Example"}, 
    "commit"=>"Sign up", 
    "format"=>"user"} 

這是我在UsersController中的create方法。我使用Devise進行身份驗證,但仍然有一個UsersController,主要是因爲它更容易理解。

def create 
    @user = User.create(:email => params[:email], :password => params[:password], 
     :password_confirmation => params[:password_confirmation], :username => params[:username], 
     :teacher => params[:teacher], :role => "student") 
    @user.save! 
end 

我知道create應該救你,但如果我不顯式調用它,然後在用戶模式不會保存到數據庫中。

最後,這裏是我試圖從中獲取數據的表單。這裏的用例是一個admin用戶將使用它來註冊students

<h2>Sign up</h2> 

<%= form_for(resource, :as => resource_name, :url => user_registration_path(resource_name)) do |f| %> 
    <%= devise_error_messages! %> 

    <div><%= f.label :email %><br /> 
    <%= f.email_field :email, :autofocus => true %></div> 

    <div><%= f.label :password %><br /> 
    <%= f.password_field :password %></div> 

    <div><%= f.label :password_confirmation %><br /> 
    <%= f.password_field :password_confirmation %></div> 

    <div><%= f.label :username %><br /> 
    <%= f.text_field :username %></div> 

    <div><%= f.label :teacher %><br /> 
    <%= f.text_field :teacher %></div> 

    <div><%= f.submit "Sign up" %></div> 
<% end %> 

回答

1

如果您發現您的:params哈希,你會看到用戶表單本身user項下提交的哈希值。

所以​​實際上是空的。你應該做params[:user][:email]

此外,你可以讓你的控制器動作即使是簡單的:

def create 
    @user = User.create(params[:user]) 
    @user.role = "student" 
    @user.save! 
end 
+0

不能要求一個更好的答案,我一直拉我的頭髮在這個笑。謝謝! – Houdini 2013-04-29 01:54:17

+0

不客氣! – AlexBrand 2013-04-29 01:57:12

相關問題