Joe*_*ing 2 ruby ruby-on-rails
我在 rails 控制器中有signup和signinPOST 路由。signup需要一个email,password和password_confirmation。signin需要一个email和password。
以下是路线的样子:
class Api::V1::AuthController < ApplicationController
def signup
binding.pry <-- inspect the params here
@user = User.create(user_credential_params)
if @user.valid?
@token = encode_token(:user_id => @user.id)
render json: { :user => @user, :jwt => @token }, :status => :created
else
render json: { :error => 'Failed to create user' }, :status => :not_acceptable
end
end
def signin
@user = User.find_by(:email => user_credential_params[:email])
# authenticate method comes from bcrypt
if @user && @user.authenticate(user_credential_params[:password])
@token = encode_token({ :user_id => @user.id })
render json: { :user => @user, :jwt => @token }, :status => :accepted
else
render json: { :error => 'Invalid credentials' }, :status => :unauthorized
end
end
private
def user_credential_params
params.permit(:email, :password, :password_confirmation)
end
endRun Code Online (Sandbox Code Playgroud)
并且routes.rb:
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
post '/signup', to: 'auth#signup'
post '/signin', to: 'auth#signin'
end
end
endRun Code Online (Sandbox Code Playgroud)
如果我binding.pry在任一控制器操作中抛出一个来检查参数(在本例中我正在检查signup),我会看到以下参数(通过 Postman 并在浏览器中使用 AXIOS):
[1] pry(#<Api::V1::AuthController>)> params
=> <ActionController::Parameters {"email"=>"joelhoelting@aol.com", "password"=>"password123", "password_confirmation"=>"password123", "controller"=>"api/v1/auth", "action"=>"signup", "auth"=>{"email"=>"joelhoelting@aol.com", "password"=>"password123", "password_confirmation"=>"password123"}} permitted: false>
您可以看到上面的参数返回email,password和password_confirmation另一个[:auth]参数哈希中的重复项。但是,我没有提供[:auth]在邮递员或浏览器中调用的参数。
哪里[:auth]PARAM来自哪里?rails 是否会自动添加该参数,如果是,为什么?
如果上下文仍然不清楚,这里是 Github 回购: 链接到回购
是的,当发送到服务器的 JSON 没有指定任何根元素时,Ruby on Rails 会自动使用当前控制器名称包装参数。
您可以在config/initializers/wrap_parameters.rb.
| 归档时间: |
|
| 查看次数: |
119 次 |
| 最近记录: |