Ruby on Rails Monday, August 4, 2014



On Saturday, 2 August 2014 11:41:46 UTC-4, Ruby-Forum.com User wrote:
Eric Saupe wrote in post #1154001:
> First change the validates to only validate if a
> password is being passed.
>
> validates :password, length: { minimum: 6 }, :if => :password
>
>
> Second, remove the parameters for password if the are blank on your
> update
> method.
>
> if params[:password].blank?
>   params.delete(:password)
> end
>

The latter I only did, because in this case it would obviously not work,
but I was not aware of the trick for the validates function!

I think I'll have to do this for all 'validates' in my application,
because I often have the case that I will update only some of the
attributes. I wonder *why* validates looks at attributes which are not
part of the update. Is there a use case where this makes sense?


This is usually the desired behavior, because you want to ensure that the *whole* record is valid before saving.

:password is a outlier here, since it isn't persisted to the database. In your case, I might add something like:

validates :password, length: { minimum: 6 }, on: :create

Since (unless users can change their passwords) you only need to check it when creating a new record.

--Matt Jones

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/53fb439d-0a42-482c-b77e-957174e14c0b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment