London
London

Reputation: 15284

Issues with validation in rails

I have a working validation on my user model. But since we're discovered that users tend to give up during their long registration form, we've split up registration form into steps so that user can give up any time and still use the site.

I'm having issues with the first step of user registration with validations. Here is the relevant bit of my User model :

with_options :if => lambda { |u| u.current_step == "get_started" } do |user|
    user.validates :firstname, presence: true, length: { maximum: 50 }
    user.validates :surname, presence: true, length: { maximum: 50 }
    user.validates :email, presence:   true,
              format:     { with: VALID_EMAIL_REGEX }

    user.validates :password_digest, presence: true
    user.validates :password, length: { minimum: 6 }
end

This validation works perfectly. However we now added facebook so its possible to login with facebook and we have hidden fields in our form facebook_uid. So I want to validate password only if these fields are nil.

Here is how I tried to modify my current validation :

with_options :if => lambda { |u| u.current_step == "get_started" } do |user|
   user.validates :firstname, presence: true, length: { maximum: 50 }
   user.validates :surname, presence: true, length: { maximum: 50 }
   user.validates :email, presence:   true,
        format:     { with: VALID_EMAIL_REGEX }

   with_options :if => lambda { |u| u.facebook_uid.nil? } do |user|
     user.validates :password_digest, presence: true
   end

   with_options :if => lambda { |u| u.user.password_digest_changed? && !u.password.nil? } do |user|
    user.validates :password, length: { minimum: 6 }
   end
end

Or inline (the relevant password part only) :

user.validates :password_digest, presence: true, if: lambda { |u| u.facebook_uid.nil? }
user.validates :password, length: { minimum: 6 }, if: lambda { |u| u.user.password_digest_changed? && !u.password.nil? }

None of these worked for me, whatever I tried I get this error :

undefined method `user' for #<User:0x00000008e924a8>

Again if I remove ifs and lambdas works as charm. Is there another way of accomplishing this or something I'm currently doing wrong with my code?

Upvotes: 0

Views: 189

Answers (1)

Jakob S
Jakob S

Reputation: 20145

In your password validation lambda, you're calling

u.user.password_digest_changed? && !u.password.nil?

ie, you're sending a user method to the u object, which is your User instance. That object doesn't respond to user. You probably just want

u.password_digest_changed? && !u.password.nil?

Upvotes: 1

Related Questions