Rails are checked only when creating or updating a user

I have validates_confirmation_of :password in my User model. The problem is that I also run @comment.user.save! when a comment is created to update some attributes in the user account.

I get an error when creating a comment Validation failed: Password confirmation can't be blank . I cannot add :on => "save" to my check because my comments controller also calls the save function.

I read this topic Validating the Rails model for creation and updating only , but it does not answer my specific problem.

UPDATE Fragment of user model:

 class User < ActiveRecord::Base attr_accessor :password # validations validates_presence_of :username validates_length_of :username, :within => 6..25 validates_uniqueness_of :username validates_presence_of :email validates_length_of :email, :maximum => 100 validates_format_of :email, :with => EMAIL_REGEX validates_confirmation_of :password, :if => :password_changed? validates_presence_of :password_confirmation validates_length_of :password, :within => 4..25, :on => :create before_save :create_hashed_password after_save :clear_password private def clear_password self.password = nil end end 
+4
source share
2 answers

Accordingly, the validates_confirmation_of model must be valid if the password_confirmation field is zero. Do you store it in DDBB? Or maybe something is wrong with your check, can you insert your user model here?

Anyway, you can try something like this:

 validates_presence_of :password_confirmation, if: -> { password.present? } validates_confirmation_of :password, if: -> { password.present? } 
+6
source

Why exactly do you run @comment.user.save! ? Touching (for example, updating timestamps) and increasing the number of comments can be done using built-in mechanisms.


Edit: I would suggest something similar to:

 class Comment < ActiveRecord::Base after_save :rank_user def rank_user # calculate rank user.update_attribute(:rank, rank) end end 

The advantages of this approach:

  • Your controller and models will be clean, and rank_user will be called automatically, without explicitly calling @comment.user.save! .
  • According to the update_attribute documentation, checks will be skipped, which will not lead to password confirmation errors.
+6
source

Source: https://habr.com/ru/post/1369474/


All Articles