Devise Ask Question で登録フィールドを追加する

Devise Ask Question で登録フィールドを追加する

私は、registrations#new にいくつかの追加フィールドを追加しようとしています。必要なのは追加データのみで、異なる機能は必要ないので、コントローラーなどをオーバーライドする必要がある理由がわかりません。そこで、registrations#new を次のように変更しました。

%h2
  Sign up
= form_for(resource, as: resource_name, url: registration_path(resource_name)) do ||f
  = devise_error_messages!
  %div
    = f.label :email
    %br
    = f.email_field :email, autofocus: true
  %div
    = f.label :title_id
    %br
    = f.text_field :title_id
  %div
    = f.label :province_id
    %br
    = f.text_field :province_id
  %div
    = f.label :first_name
    %br
    = f.text_field :first_name
  %div
    = f.label :last_name
    %br
    = f.text_field :last_name
  %div
    = f.label :password
    %br
    = f.password_field :password
  %div
    = f.label :password_confirmation
    %br
    = f.password_field :password_confirmation
  %div= f.submit 'Sign up'
= render 'devise/shared/links'

サニタイザーを通じてこれらの追加フィールドを有効にするために、ApplicationController を次のように更新しました。

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  before_filter :store_requested_url!
  # before_filter :authenticate_user!

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:email) }
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:email, :password, :password_confirmation, :title_id, :province_id, :first_name, :last_name) }
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:email, :password, :password_confirmation, :current_password) }
  end

  def after_sign_in_path_for(resource)
    session[:requested_url] || root_path
  end

  private

  def store_requested_url
    # store last url as long as it isn't a /users path
    session[:previous_url] = request.fullpath unless request.fullpath == /\/users/
  end
end

何らかの理由で、これは機能せず、余分なフィールドは null としてデータベースに送られます。

私は Ruby 2 と Rails 4 rc1、Devise 3.0.0.rc を使用しています。

ベストアンサー1

質問のコード サンプルは、サニタイザーを呼び出す before_filter を設定していないために機能していないようです。

before_filter :configure_permitted_parameters, if: :devise_controller?

そうは言っても、承認された回答に示されているように、コントローラをオーバーライドして、アプリケーションコントローラが常にこのチェックを行わないようにする方が良いでしょう。承認された回答は、以下のコードで短縮できます。このコードを自分のアプリケーションでテストしましたが、うまく機能しました。これらはすべて、README3.0.0.rc タグ内。

コントローラーをオーバーライドします。

class RegistrationsController < Devise::RegistrationsController
  before_filter :configure_permitted_parameters, :only => [:create]

  protected

    def configure_permitted_parameters
      devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password) }
    end
end

次に、それを使用するためにルートを更新します。

devise_for :members, :controllers => { :registrations => "registrations" }

おすすめ記事