1

尝试从 json 请求创建用户,但我的服务器给了我“typeError(没有将 Symbol 隐式转换为 Integer)”。我知道我的嵌套属性有问题,但我不知道是什么,这让我发疯..

我的 Javascript 文件:

user = {
    email: @get('email')
    first_name: @get('firstName')
    last_name: @get('lastName')
    password: @get('password')
    password_confirmation: @get('passwordConfirmation')
    registration_completed: true

    authentications_attributes: {
        provider: @get('provider')
        uid: @get('uid')
    }
}

$.post("/api/users", { user })

参数:

params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :registration_completed, authentications_attributes: [:id, :user_id, :provider, :uid])

安慰:

Started POST "/api/users" for 127.0.0.1 at 2013-09-20 15:39:49 +0200
Processing by Api::UsersController#create as */*
  Parameters: {"user"=>{"email"=>"foo@example.com", "first_name"=>"Foo", "last_name"=>"Bar", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "registration_completed"=>"true", "authentications_attributes"=>{"provider"=>"facebook", "uid"=>"10000000"}}}
Completed 500 Internal Server Error in 97ms

TypeError (no implicit conversion of Symbol into Integer):
  app/controllers/api/users_controller.rb:17:in `create'

我究竟做错了什么?当然,我的 User.rb 文件中有“accepts_nested_attributes_for :authentications”。谢谢!

更新

def create      
    @user = User.new(user_params)
    @user.authentications.build
    authorize! :create, @user

    if @user.save 
      render json: { user: { id: @user.id, auth_token: @user.session_api_key } }, status: 201
    else
      render json: { errors: @user.errors.messages }, status: :unprocessable_entity
    end
end
4

2 回答 2

2

我的哈希错误,正确的哈希应该是:

user = {
    ....
    authentications_attributes: [
        {
            provider: @get('provider')
            uid: @get('uid')
        }
    ]
}
于 2013-09-23T10:49:58.097 回答
0

请试试这个,如果它不起作用,请告诉我。

def new
  @user = User.new
  @user.authentications.build
end

def create
  @user = User.new(user_params)

  respond_to do |format|
    if @user.save
      format.json { user: { id: @user.id, auth_token: @user.session_api_key } }, status: 201
    else
      format.json { errors: @user.errors.messages }, status: :unprocessable_entity
    end
  end
end

private
def user_params
  params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :registration_completed, authentications_attributes: [:provider, :uid])
end
于 2013-09-23T08:10:01.777 回答