복붙노트

[RUBY-ON-RAILS] 레일 4.0에서 고안에 새로운 필드를 추가 허가되지 않은 매개 변수

RUBY-ON-RAILS

레일 4.0에서 고안에 새로운 필드를 추가 허가되지 않은 매개 변수

레일 작업에 아주 새로운. 내가 고안를 사용하여 기본적인 로그인 시스템을 구현했습니다. sign_up 페이지에 (문자열 : 문자열, 이름 바이오) 나는 새로운 분야의 몇 가지를 추가하려합니다. 나는 그러나, 그들이 채우고 사용자 제출하는 sign_up 양식 후에 그것의 일부라는 메시지가 없습니다 모든 것이 제대로 표시하고 (나는 SQLbrowser에서 볼 때) 새로운 필드가 데이터베이스에 추가되어 있습니다 :

Unpermitted parameters: bio, name

나는 _devise_create_users.rb에이 문자열을 추가 한

  # added
  t.string :bio
  t.string :name

그리고 나는 그들이 schema.rb에 표시해야

ActiveRecord::Schema.define(version: 20130629002343) do

  create_table "users", force: true do |t|
    t.string   "email",                  default: "",    null: false
    t.string   "encrypted_password",     default: "",    null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "shortbio"
    t.boolean  "admin",                  default: false
    t.string   "realname"
    t.string   "name"
    t.string   "bio"
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

end

내 user.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
   #:token_authenticatable, :confirmable,
   #:lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

end

강력한 매개 변수와 함께 할이 문제가 뭔가인가? 나는 힘든 시간을 그들 주위에 내 머리를 감싸고 / 방법을 구현하는 방법을 데.

해결법

  1. ==============================

    1.허용되는 솔루션은 충분히 좋은,하지만 난 두 가지 문제를 참조하십시오 : devise_controller), 2) 우리는 방법의 모든 허용 매개 변수를 (작성해야하는 경우 현재의 컨트롤러 (유증 컨트롤러 인 경우 1) 모든 컨트롤러를 확인합니다 ...에 대한 (: sign_up) {| 유 | u.permit (: 바이오 : 이름)}), 심지어 : 이메일 : 암호 등등.

    허용되는 솔루션은 충분히 좋은,하지만 난 두 가지 문제를 참조하십시오 : devise_controller), 2) 우리는 방법의 모든 허용 매개 변수를 (작성해야하는 경우 현재의 컨트롤러 (유증 컨트롤러 인 경우 1) 모든 컨트롤러를 확인합니다 ...에 대한 (: sign_up) {| 유 | u.permit (: 바이오 : 이름)}), 심지어 : 이메일 : 암호 등등.

    나는 더 우아한 해결책이 될 수 있다고 생각한다 :

    # app/controllers/users/registrations_controller.rb
    class Users::RegistrationsController < Devise::RegistrationsController
      before_filter :configure_permitted_parameters
    
      protected
    
      def configure_permitted_parameters
        devise_parameter_sanitizer.for(:sign_up).push(:name, :phone, :organization)
      end
    end
    
    # config/routes.rb
    devise_for :users, :controllers => { :registrations => "users/registrations" }
    

    참고 : 레일에 대한 업데이트 4.2 이상

    이 대답은 유효 기간이 떨어지고 :

  2. ==============================

    2.당신이 적어도 고안 3.0.0를 사용하고 있는지 확인. 응용 프로그램 컨트롤러에 추가

    당신이 적어도 고안 3.0.0를 사용하고 있는지 확인. 응용 프로그램 컨트롤러에 추가

    before_filter :update_sanitized_params, if: :devise_controller?
    
    def update_sanitized_params
      devise_parameter_sanitizer.for(:sign_up) {|u| u.permit(:bio, :name)}
    end
    

    문서 : https://github.com/plataformatec/devise#strong-parameters

  3. ==============================

    3.나도이에 문제가 있었다. 유증의 사이트에있는 문서는 일부 포럼뿐만 아니라 도움을 주었다. 여기에 내가하고 결국 무엇을 :

    나도이에 문제가 있었다. 유증의 사이트에있는 문서는 일부 포럼뿐만 아니라 도움을 주었다. 여기에 내가하고 결국 무엇을 :

    사용자 정의 RegistrationsController에서 (응용 프로그램 / 컨트롤러 / 사용자 / registrations_controller.rb)

    # app/controllers/users/registrations_controller.rb
    
    class Users::RegistrationsController < Devise::RegistrationsController
        before_filter :update_sanitized_params, if: :devise_controller?
    
        def update_sanitized_params
           devise_parameter_sanitizer.for(:sign_up) {|u| u.permit(:name, :email,   :password, :password_confirmation)}
        end
    end
    

    그런 다음 경로 파일 (설정 / routes.rb)에 devise_for 문에 대한 우리이 :

    devise_for :users, controllers: {registrations: "users/registrations"}
    
  4. ==============================

    4.여기 내 레일 4.2.1 응용 프로그램에서 작동 다른 똑 바른 앞으로 방법이있다 :

    여기 내 레일 4.2.1 응용 프로그램에서 작동 다른 똑 바른 앞으로 방법이있다 :

    다음 파일을 생성

    /config/initializers/devise_permitted_parameters.rb
    

    및 코드 ..

    module DevisePermittedParameters
      extend ActiveSupport::Concern
    
      included do
        before_filter :configure_permitted_parameters
      end
    
      protected
    
      def configure_permitted_parameters
        devise_parameter_sanitizer.for(:sign_up) << :name
        devise_parameter_sanitizer.for(:account_update) << :name
    
        devise_parameter_sanitizer.for(:sign_up) << :bio
        devise_parameter_sanitizer.for(:account_update) << :bio
      end
    
    end
    
    DeviseController.send :include, DevisePermittedParameters
    
  5. ==============================

    5.sign_up 및 account_update 모두 들어 컨트롤러에 대해이 작업을 수행 / applcation_controller.rb을

    sign_up 및 account_update 모두 들어 컨트롤러에 대해이 작업을 수행 / applcation_controller.rb을

    class ApplicationController < ActionController::Base
      protect_from_forgery with: :exception
      before_action :authenticate_user!
    
      before_action :configure_permitted_parameters, if: :devise_controller?
      protected
      def configure_permitted_parameters
        devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:password, :password_confirmation,:current_password,:email,:name, :phonenumber,:province,:city,:area,:idcardimg,:role) }
        devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:password, :password_confirmation,:current_password,:email,:name, :phonenumber,:province,:city,:area,:idcardimg,:role) }
      end
    end
    
  6. ==============================

    6.문제는 강한 매개 변수, 여기보고 코드를 복사 보인다.

    문제는 강한 매개 변수, 여기보고 코드를 복사 보인다.

    https://github.com/plataformatec/devise/blob/rails4/app/controllers/devise/registrations_controller.rb

    프로젝트 응용 프로그램 / 컨트롤러 / 궁리 / registrations_controller.rb에서 같은 위치에 해당 파일을 복사

    그리고 만드는 행동의 코드를 변경

    # POST /resource
    def create
      # THIS LINE IS THE ONE YOU CHANGE
      self.resource = build_resource(sign_up_params.merge(:bio, :name))
    
      if resource.save
        if resource.active_for_authentication?
          set_flash_message :notice, :signed_up if is_navigational_format?
          sign_up(resource_name, resource)
          respond_with resource, :location => after_sign_up_path_for(resource)
        else
          set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
          expire_session_data_after_sign_in!
          respond_with resource, :location => after_inactive_sign_up_path_for(resource)
        end
      else
        clean_up_passwords resource
        respond_with resource
      end
    end
    

    나는이 작품을 내가 장치를 사용하지만 작동 보인다 코드가 표시되지 않기 때문에 만약 내가 꽤 잘 모르겠어요 사실을 알려야합니다.

  7. ==============================

    7.그것을위한 준비가 모든 것을 고안 :

    그것을위한 준비가 모든 것을 고안 :

    사용자는 당신이 컨트롤러

    private
    
    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params.require(:user).permit(:full_name <add your parameter>)
    end
    
  8. from https://stackoverflow.com/questions/17384289/unpermitted-parameters-adding-new-fields-to-devise-in-rails-4-0 by cc-by-sa and MIT license