Ruby on Rails
Monday, August 4, 2014
I generally avoid code like that because it creates OOO dependancies (but in a small app might work fine).
In fact you've stumbled onto one of the really smelly parts of Rails, IMHO.
What I usually do in cases like these (in fact I'm working on something right at this moment) is that I enforce User objects to have a state ("new", "onboarding", "registered", etc) and then enforce the validations only in certain states.
validates :password, if: lambda { self.registration_state == "registered" }
This is actually tedious to do, but writing code this way creates a better long-term implementation because it enforces rules in a more maintainable way. If you don't do this and you start down the path of callbacks & validation headaches and those are always nasty (which, from the sound of things, you are probably already in.)
Also, read this book:
On Aug 4, 2014, at 3:30 PM, Matt Jones <al2o3cr@gmail.com> wrote:
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: :createSince (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.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment