Strong parameters with has_many gives “no implicit conversion of Symbol into Integer”

只谈情不闲聊 提交于 2020-01-16 01:26:44

问题


Trying to create a user from a json request but my server gives me "typeError (no implicit conversion of Symbol into Integer)". I understand that it's something wrong with my nested attribute but i dont know what, this's driving me crazy..

My Javascript file:

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:

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

Console:

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'

What am I doing wrong? And of course have i "accepts_nested_attributes_for :authentications" in my User.rb file. Thanks!

UPDATE

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

回答1:


My hash was wrong, right hash should be:

user = {
    ....
    authentications_attributes: [
        {
            provider: @get('provider')
            uid: @get('uid')
        }
    ]
}



回答2:


Please try this and let me know if it wont work.

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


来源:https://stackoverflow.com/questions/18918337/strong-parameters-with-has-many-gives-no-implicit-conversion-of-symbol-into-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!