Skip to content

Instantly share code, notes, and snippets.

@BGuimberteau
Last active May 18, 2018 08:25
Show Gist options
  • Save BGuimberteau/4da1ab54e576121edde5 to your computer and use it in GitHub Desktop.
Save BGuimberteau/4da1ab54e576121edde5 to your computer and use it in GitHub Desktop.
Strong parameters with grape
module StrongParamsHelpers
extend Grape::API::Helpers
def permitted_params
@permitted_params ||= declared(params, include_missing: false, include_parent_namespaces: false)
end
end
module V1
class Users < Grape::API
helpers StrongParamsHelpers
resource :users do
desc 'Create a new user'
params do
requires :user, type: Hash do
requires :last_name, type: String, desc: 'Last name'
requires :first_name, type: String, desc: 'First name'
requires :email, type: String, desc: 'Email address'
requires :phone, type: String, desc: 'Phone number'
requires :password, type: String, desc: 'Password'
end
end
post do
can_be_here? User
@user = User.new permitted_params[:user]
@user.save!
@user
end
end
end
end
@simpl1g
Copy link

simpl1g commented Jul 1, 2016

    def permitted_params
      ActionController::Parameters.new(declared(params, include_missing: false)).permit!
    end

This helps in Rails 5

@MohdAnas
Copy link

MohdAnas commented Feb 28, 2017

Not able to update by using

def permitted_params ActionController::Parameters.new(declared(params, include_missing: false)).permit! end

Did anyone resolve this issue?

Thanks

@AndrewThian
Copy link

AndrewThian commented Jul 31, 2017

@MohdAnas
Managed to update via self.assign_attributes:

def update_credentials(params)
    self.assign_attributes(whitelist_params(params, attributes.keys))
    self.save!
end

def whitelist_params(params, attrs)
    whitelisted = {}
    attrs.each do |attr|
      whitelisted[attr.to_sym] = params[attr] if params[attr]
    end

   whitelisted
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment