Rails 4.0 和 Devise 的强大参数
Strong parameters with Rails 4.0 and Devise
我正在使用 Rails 4.2,devise.Request 类型将始终是 JSON.My 注册控制器看起来像这样
class Users::RegistrationsController < Devise::RegistrationsController
before_filter :configure_sign_up_params, only: [:create]
def create
if request.format(request) == "application/json"
build_resource(sign_up_params)
if resource.save
render :json => {:success => "true", :message => "Thank You For Registering."}
else
render :json => {:success => "false", :message => resource.errors.full_messages}
end
else
super
end
end
protected
def configure_sign_up_params
devise_parameter_sanitizer.for(:sign_up) do |u|
u.permit(:email, :password, :password_confirmation)
end
end
end
控制台中显示的参数如下:
Parameters: {"email"=>"test123@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "registration"=>{"email"=>"test123@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}}
它产生的错误是控制器无法识别电子邮件和密码字段,并且总是 returns 错误,如:
["Email can't be blank","Password can't be blank"]
会不会是我在代码中写的愚蠢导致的?请帮忙
您的 configure_sign_up_params
方法必须像这样才能起作用。
def configure_sign_up_params
devise_parameter_sanitizer.for(:registration) do |u|
u.permit(:email, :password, :password_confirmation)
end
end
如果您可以看到您发布的控制台内容,它包含一个以 registration
作为键的散列:
"registration"=>{"email"=>"test123@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}
我正在使用 Rails 4.2,devise.Request 类型将始终是 JSON.My 注册控制器看起来像这样
class Users::RegistrationsController < Devise::RegistrationsController
before_filter :configure_sign_up_params, only: [:create]
def create
if request.format(request) == "application/json"
build_resource(sign_up_params)
if resource.save
render :json => {:success => "true", :message => "Thank You For Registering."}
else
render :json => {:success => "false", :message => resource.errors.full_messages}
end
else
super
end
end
protected
def configure_sign_up_params
devise_parameter_sanitizer.for(:sign_up) do |u|
u.permit(:email, :password, :password_confirmation)
end
end
end
控制台中显示的参数如下:
Parameters: {"email"=>"test123@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "registration"=>{"email"=>"test123@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}}
它产生的错误是控制器无法识别电子邮件和密码字段,并且总是 returns 错误,如:
["Email can't be blank","Password can't be blank"]
会不会是我在代码中写的愚蠢导致的?请帮忙
您的 configure_sign_up_params
方法必须像这样才能起作用。
def configure_sign_up_params
devise_parameter_sanitizer.for(:registration) do |u|
u.permit(:email, :password, :password_confirmation)
end
end
如果您可以看到您发布的控制台内容,它包含一个以 registration
作为键的散列:
"registration"=>{"email"=>"test123@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}