简体   繁体   中英

Rails 4 - sending devise params to a User model method

i have my own RegistrationsController , which inherits from Devise. In update I want to send params to my User method like above:

def update
   params = resource.delete_invoice(params) if resource.check_invoice(params[:user])
   if params[:user][:name].blank?
      flash[:alert] = t 'devise.registrations.wrong_user_name'
      redirect_to action: 'edit' and return
  end
  super
end

Unfortunatelly i get error:

NoMethodError in Users::RegistrationsController#update, undefined method `[]' for nil:NilClass 

It's strange because I can normally write puts params and it's not empty. How can I resolve this?

Try this:

unless params[:user].blank?
  if params[:user][:name].blank?
    #do your stuff
  end
end

The error here is that it is trying to call [] on a nil object, as it is very unlikely that params or flash is nil, the only other place you call [] is on params[:user] which suggests that this is nil.

Couple of options, check if params[:user] is nil or use try:

if params[:user].nil? or params[:user][:name].blank?
      flash[:alert] = t 'devise.registrations.wrong_user_name'
      redirect_to action: 'edit' and return
end  

Alternatively:

if params[:user].try(:fetch, :name).try(:blank?)
      flash[:alert] = t 'devise.registrations.wrong_user_name'
      redirect_to action: 'edit' and return
end

Which I think is neater. NB try is a rails method, not ruby.

Are you sure the resource is built when you run update? In Rails 4 the build_resource is being built inside that method devise/registrations_controller . Probably you want to use resource_class ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM