Gem grape 如何处理 StrongParameters?

stephen · July 09, 2014 · Last by googya replied at March 04, 2015 · 3106 hits

用 grape 编写api/users/sign_up.json 代码

resource :users do
   post "sign_up" do
      # 不添加下面这句,会出现ActiveModel::ForbiddenAttributesError - ActiveModel::ForbiddenAttributesError:错误
      # 添加了后出现TypeError - no implicit conversion of Symbol into String:错误
      user_params = params.require(:user).permit(:email, :password, :password_confirmation)
      @user = User.new(user_params)
      if (params[:user][:password].length > 8) && (params[:user][:password] == params[:user][:password_confirmation]) && @user.save
        { :success => 1, :auth_token => @user.authentication_token, :email => @user.email }
      else
        { :success => 0, :auth_token => "", :email => "" }
      end
    end
end

不添加下面这句,会出现 ActiveModel::ForbiddenAttributesError - ActiveModel::ForbiddenAttributesError:错误 添加了后出现 TypeError - no implicit conversion of Symbol into String:错误 user_params = params.require(:user).permit(:email, :password, :password_confirmation) GG 过,解决不了! 这个错误怎么解决?

可以用下面控制参数么

params do
...
end

ActionController::Parameters.new(parameters)

params do
  requires :blah, type: Integer
end

get do
  @blah = declared(params, include_missing: false)[:blah]
end

@sunday35034 @flypiggys 这种方法和我添加那一句代码应该是相同作用的!修改后,出现的错误一样!

#2 楼 @ruby_sky 直接在 api 里添加?

#5 楼 @stephen

user_params = ActionController::Parameters.new(params[:user])
user_params.require(:user).permit(:email, :password, :password_confirmation)

这种方式是自己封装 Helper 处理。

@Victor @ruby_sky 谢谢!已经解决!

#6 楼 @Victor 即便是这样,还是有问题啊,

 t = Prescription.create(declared(params, include_missing: false))

ActiveModel::ForbiddenAttributesError: ActiveModel::ForbiddenAttributesError
from /Users/leslie/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/forbidden_attributes_protection.rb:21:in `sanitize_for_mass_assignment'

后来发现是我自己把参数多带了。。。。

You need to Sign in before reply, if you don't have an account, please Sign up first.