2016-03-28 19 views
1

我向模型用戶添加了列信息,這是由設計生成的。我不想讓用戶通過註冊填寫字段信息。我爲其他頁面創建了控制器,如配置文件如何用params獲得正確的信息?

class PagesController < ApplicationController 

    def myprofile 
    @currentUser = User.find_by_id(current_user.id) 
    end 

    def userinfo 
    @currentUser = User.find_by_id(current_user.id) 

    if request.post? 
     if @currentUser.update(params[:userinfo].permit(:information)) 
     redirect_to myprofile_path 
     else 
     render 'userinfo' 
     end 
    end 
    end 

end 

頁面userinfo用戶應該能夠編輯他的信息。

這裏是視圖:

<div id="page_wrapper"> 

    <h2>Hey, <%= @currentUser.username %>, add some information about you: </h2> 
    <%= form_for @currentUser.information do |f| %> 
    <p> 
     <%= f.label :information %><br /> 
     <%= f.text_area :information, autofocus: true %> 
    <p> 

    <p> 
     <%= f.submit "Save" %> 
    <p> 
    <% end %> 

</div> 

應用控制器:

class ApplicationController < ActionController::Base 
    protect_from_forgery with: :exception 
    before_action :configure_permitted_parameters, if: :devise_controller? 

    protected 
    def configure_permitted_parameters 
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :information, :email, :password, :password_confirmation, :remember_me) } 
    devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:login, :information, :email, :password, :remember_me) } 
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:username, :information, :email, :password, :password_confirmation, :current_password) } 
    end 
end 

當我試圖挽救它,我得到

未定義的方法'許可證」的零:NilClass

我該如何解決它?也許有更好的方法來完成這項工作?我不想顯示整個表單來編輯密碼,用戶名等信息。

回答

0

未定義的方法'許可證」的零:NilClass

你做錯了。您的params將不包含:userinfo密鑰。你的params看起來像這樣:user => {:information => 'value'}。你應該爲你想更新一定的記錄更改您的代碼如下

#controller 
def userinfo 
    @currentUser = User.find_by_id(current_user.id) 

    if @currentUser.update(user_params) 
    redirect_to myprofile_path 
    else 
    render 'userinfo' 
    end 
end 

protected 
def user_params 
    params.require(:user).permit(:information) 
end 

而且也,你需要改變

<%= form_for @currentUser.information do |f| %> 

<%= form_for @currentUser, method: put do |f| %> 

最後如果您爲此相應的controller#action設置了post路線,則y ou需要將其更改爲put

+0

謝謝,但現在我收到其他錯誤。 參數丟失或值爲空:用戶 爲什麼會發生? – malworm

+0

@bg_mi你可以發佈生成的參數的輸出嗎? – Pavan

+0

這是http://snag.gy/7b7ys.jpg,你的意思是? – malworm

相關問題