How to avoid the validation, callbacks and 'at

2020-02-29 11:02发布

问题:

I am using Ruby on Rails 3 and I am trying to seed data in my application database.

In 'RAILS_ROOT/models/user.rb' I have:

class User < ActiveRecord::Base
  attr_accessible #none

  validates :name,
    :presence => true
  validates :surname,
    :presence => true
  validates :email,
    :presence => true
end

In 'RAILS_ROOT/db/seeds.rb' I have:

# Test 1
User.find_or_create_by_email (
  :name       => "Test1 name",
  :surname    => "Test1 surname",
  :email      => "test1@test1.test1"
)

# Test2
User.find_or_create_by_email (
  :name       => "",
  :surname    => "",
  :email      => "test2@test2.test2"
)

So, running in the Terminal

rake db:seed

of course the database will NOT populate with datas because 'attr_accessible' to nil (Case Test1) and validation not passed (Case Test2).

I would like to skip the validation and "attr-accessible effects" during the seeding process. Is it possible? If so, how to do that?

P.S.: I don't want to use in 'RAILS_ROOT/db/migrate/201....rb' code like this:

execute "INSERT INTO users ( name, surname, email ) VALUES ( "Test1 name", "Test1 surname", "test1@test1.test1")"

UPDATE

I need also to skip all callbacks. Is it possible? If so, how?

回答1:

If you check ActiveRecord's documentation you'll see the attributes= method has a parameter to enable this:

attributes=(new_attributes, guard_protected_attributes = true)

Use it like this:

# Create a new user
@user = User.new

# Attributes for the user
@attrib = {
  :name       => "Test1 name",
  :surname    => "Test1 surname",
  :email      => "test1@test1.test1"
}

# Use 'send' to call the attributes= method on the object
@user.send :attributes=, @attrib, false

# Save the object
@user.save