Reputation: 3090
To my User model I have added a new variable new_email
. To this end I added:
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :new_email, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX }
In migration file:
t.string :new_email
I have not added anything in my seeds file regarding this new variable. On seeding I get the error: ActiveRecord::RecordInvalid: Validation failed: New email is invalid
. If I remove the validates
line from the model file it seeds succesfully. I have tried resetting my db: rake db:drop
, rake db:create
, rake db:migrate
and rake db:seed
, but with the same result. What could be causing this error?
The controller methods using params:
def create
@user = User.new(usernew_params)
if @user.save
@user.send_activation_email
flash[:success] = "A confirmation email has been sent to you"
redirect_to root_url
else
render 'new'
end
end
def update
@user = User.friendly.find(params[:id])
if @user.update_attributes(userupdate_params)
flash[:success] = "Profile updated"
redirect_to @user
else
render 'edit'
end
end
private
def usernew_params
params.require(:user).permit(:email,
:username,
:password,
:password_confirmation)
end
def userupdate_params
params.require(:user).permit(:email,
:email_new,
:avatar,
:organization,
:activated,
:password,
:password_confirmation)
end
And my seeds file (left out other models without a relationship to this model):
99.times do |n|
username = "fakename#{n+1}"
email = "example-#{n+1}@railstutorial.org"
password = "password"
organization = Faker::Company.name
User.create!(username: username,
email: email,
password: password,
password_confirmation: password,
activated: true,
activated_at: Time.zone.now,
organization: organization)
end
Upvotes: 0
Views: 1058
Reputation: 29328
The issue is that you are validating new_email
on every request and not allowing it to be blank. Since it is not set in your seed file and you are validating based on a Regexp
this will fail every time.
Based on your use case described I would recommend this
validates :new_email, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
allow_blank: true,
on: :update
This will do 2 things:
new_email
to be blank ""
or omitted completely nil
without failing. new_email
on create through the controller this validation will only run on update
. While validations that allow_blank
are fairly lightweight I still try to advise against running code when it is not needed that is why I added the on
parameter.
Upvotes: 0