How to avoid the validation, callbacks and 'attr_accessible' effects during the seeding process using Ruby on Rails 3?

后端 未结 1 1700
半阙折子戏
半阙折子戏 2021-01-03 12:37

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 < ActiveRe         


        
相关标签:
1条回答
  • 2021-01-03 13:08

    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
    

    0 讨论(0)
提交回复
热议问题