簡體   English   中英

如何獲得帶有參數的正確信息?

[英]How can I get correct infromation with params?

我將列信息添加到模型User中,該信息是由devise生成的。 我不想讓用戶通過注冊來填寫字段信息。 我為個人資料等其他頁面創建了控制器

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

當我嘗試保存它時,我得到

nil:NilClass的未定義方法“ permit”

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

nil:NilClass的未定義方法“ permit”

你做錯了。 您的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路線,則需要將其更改為put

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM