简体   繁体   中英

Filling table with values during migration doesn't work completely

My Users table being quite big, I decided to migrate user profile information to a separate table: Profiles . So Users table will only have access information (using Devise gem). A Profile can have many user accesses.

To do so, I created a migration file to write new data in Profiles table, from Users table:

class MigrateSomeUsersInfoToProfilesTable < ActiveRecord::Migration
  def up

    puts "Pulling out profile information from Users table. Can take a while..."
    puts "Start migrating #{User.count} users to `Profiles` table (#{Profile.count} profiles already created)..."

    User.all.each do |u|

      profile = Profile.new({
        first_name: u.first_name,
        last_name: u.last_name,
        picture: u.picture,
        zipcode: u.zipcode,
        bio: u.bio,
        address: u.address,
        latitude: u.latitude,
        longitude: u.longitude,
        gender: u.gender
      })

      if profile.save!
        u.profile_id = profile.id
        u.save!
      else
        puts "ERROR CREATING PROFILE FOR USER #ID #{u.id}"
      end

      puts "CREATED PROFILE ##{profile.id} FOR USER ##{u.id}"

    end
  end

  def down
    Profile.delete_all
  end
end

The result is that all profiles were created (the same number as users) and correcly filled. But, the profile_id is nil for all users. This means that the line u.profile_id = profile.id isn't correctly executed.

The only log messages I get are those specified in the migration file (no error or warning messages).

Is there something I missed in the code bellow? Thanks.

UPDATE

From rails console I get:

User.count
=> 2182

Profile.count
=> 2182

User.where("profile_id IS NULL").count
=> 2182

UPDATE 2

In the app, a real user (defined by the information in Profiles table) can access the app using many emails (personnal, professional,...). In this case, the models are like the following:

class User < ActiveRecord::Base
  belongs_to :profile
end

class Profile < ActiveRecord::Base
  has_many :users
end

That's why, there is a profile_id in the Users table (attribute that is not updated during the migration??)

I think you should use user_id not profile_id if you use the following association:

class Profile < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_one :profile
end

# tables
"profiles"
id: integer
user_id: integer

"users"
id: integer

http://guides.rubyonrails.org/association_basics.html#the-belongs-to-association

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM