Home > Back-end >  Rails Controller runs update function anyway even though the form submit returns devise error messag
Rails Controller runs update function anyway even though the form submit returns devise error messag

Time:08-14

Environment:

rails 4.2.6
devise 4.1.1

I am using a rails app, and there is a form to update user's profile. By default, devise asks the user to input user's password to update the user's data. I have put the <%=devise_error_messages! %> in the form, of course there is a update function in the controller, which looks like

def update
  super
  @email = resource.email
  @event = resource.event
  @name = resource.name
  NoticeMailer.notice_confirm(@email, @name, @event).deliver_later
end

Here comes the problem. When I am editing the user's profile data, by default, devise asks the user to input the password to update the data and save it to the database. If I input the wrong password or leave the password field blank, and press the submi button(form.submit), there will be an error message, and I am still in the form. However even though there is an error message in the form, the update function in the controller still runs anyway. I think the logic is that the update function should not run if the update is failed.

Try01: Try to input the data without password. I use the method

protected 
  def resource_update(params, resource)
     resouce.update_without_password(params, resource)
  end

in the controller,but it threw error message.

Try02 I am thinking using ajax to catch the submit click action and pass the password field to backend to check password. however i don't know how to implement this.

Try03

I tried to put a after_update filter function to do the mail sending function. However the result is the same, the mail function is sending no matter what.

Any suggestion?

CodePudding user response:

I would expect the resource to be not valid? if the update failed. Therefore I would try:

def update
  super

  NoticeMailer.notice_confirm(
    resource.email, resource.name, resource.event
  ).deliver_later if resource.valid?
end

Btw unless you use the instance variables somewhere else in the same controller or its view then it should not be required assigning value to them first but you could pass the values directly to the mailer.

CodePudding user response:

The correct update function in the controller:

def update
  super
  @email = resource.email
  @event = resource.event
  @name = resource.name
  unless resource.errors.any?
    NoticeMailer.notice_confirm(@email, @name, @event).deliver_later
  end
end

Update02

def update
  super
  NoticeMailer.notice_confirm(
   resource.email, resouce.name, resouce.event
  ).deliver_later unless resource.errors.any?
end
  • Related