0

So I have a userMigration file which creates the rows in the table manually. This called in the initialization stage. Also, on that particular table I have validations on how the user's details should be (length, uniqueness etc).

Migration.rb

      Models::Persistence::User.create({:email => '[email protected]',
                                    :username => '[email protected]',
                                    :first => '',
                                    :last => 'User',
                                    :password => 'Test123!!',
                                    :bio => 'User, student',
                                    # :user_id => 3,
                                    # :photoURL => "http://link",
                                    :created_by => 1})

My models file for users:

  module Persistence
# Models persistent User data
class User < ActiveRecord::Base
  include Songkick::OAuth2::Model::ResourceOwner
  validates :bio, length:  {maximum: 500}

  validates_uniqueness_of :email
  validates :email, :presence => true, :allow_nil => false
  validates_format_of :email,:with => /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/

  validates :first, :presence => true, :allow_nil => false, length: {maximum: 100}
  validates_format_of :first, :with => /[a-zA-Z]/

When I change the userMigration data and put in values which do not meet the validation criteria, the rows with that data is still created. (The first name in nil in the migration file but the row is still created in the db.) Is there a way to make print out an error at this stage?

1
  • Right now, one solution I can think of is that when I try to manually create during migration, I could try validating the user. Is this the only way? Commented Mar 21, 2015 at 16:55

1 Answer 1

1

Try using the bang version: create! - it throws an error if the record is invalid.

http://guides.rubyonrails.org/active_record_validations.html#when-does-validation-happen-questionmark

Rails 3 - DB seed data validation

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.