2016-03-28 18 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

相关问题