Вопрос

I am trying to insert some default users in my project using seed.rb file. I have executed the following line in the console:

rake db:seed

and no errors were thrown, but the records were not created either. When I paste the code in the rails console, again no errors are shown. I am guessing that I am doing something wrong in the seed.rb file.

This is how my models are related:


security_user.rb

has_one :security_users_detail, dependent: :destroy
has_many :security_users_manage_securities
has_many :security_users_roles, through: :security_users_manage_securities

security_users_detail.rb

belongs_to :security_user

security_users_role.rb

has_many :security_users_manage_securities
has_many :security_users, through: :security_users_manage_securities

And this is the code that I have in my seed.rb file:

users = {

   Admin: {

      Information: {
        email: 'test@gmail.com',
        password: 'test',
        password_confirmation: 'test'
      },
      Details: {
        address: 'Not defined.',
        city: 'Not defined.',
        country: 'Not defined.',
        egn: '0000000000',
        faculty_number: '',
        first_name: 'Admin',
        gender: 'male',
        gsm: '0000000000',
        last_name: 'Not defined.',
        skype: 'Not defined.'
      },
      Roles: %w(Administrator)
   }
}

users.each do |user, data|

  security_user = SecurityUser.new(data[:Information])

  data[:Roles].each { |role|
    security_user.security_users_manage_securities.build(security_users_role: SecurityUsersRole.find_by_role(role))
  }

  SecurityUser.where(email: security_user.email).first_or_create!(security_user.attributes)

  security_users_detail = SecurityUsersDetail.new(data[:Details])
  security_users_detail.security_user_id = security_user.id
  SecurityUsersDetail.where(security_user_id:  security_users_detail.security_user_id).first_or_create

end
Это было полезно?

Решение 2

The issue was caused by the following line:

security_user = SecurityUser.new(data[:Information])

because even thought the hash passed in the new method holds only email and password fields, the result object was created with the rest of the model attributes but set to nil. For, example, I have id=>nil.

Then in I was doing the following

SecurityUser.where(email: security_user.email).first_or_create!(security_user.attributes)

in order to created the user only if exists. Anyway, since the id parameter is not in the attr_accessible clause in the model, I was not able to make mass assign.

To delete the nil values of the hash I've done the following:

 SecurityUser.where(email: security_user.email)
              .first_or_create!(security_user.attributes
              .delete_if { |key, value| value.nil? })

Другие советы

seed.rb is a rake task, so you can use puts to output messages to the console. For instance,

puts "User name: #{user.name}"
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top