繁体   English   中英

在迁移过程中用值填充表无法完全正常工作

[英]Filling table with values during migration doesn't work completely

我的用户表很大,我决定将用户个人资料信息迁移到一个单独的表: 个人档案 因此, Users表将仅具有访问信息(使用Devise gem)。 配置文件可以具有许多用户访问权限。

为此,我创建了一个迁移文件,以从Users表中的Profiles表中写入新数据:

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

结果是创建了所有概要文件(与用户数量相同)并正确填写。 但是, profile_id对所有用户均为nil 这意味着未正确执行u.profile_id = profile.id行。

我获得的唯一日志消息是在迁移文件中指定的日志消息(无错误或警告消息)。

我在代码箱中错过了什么吗? 谢谢。

更新

rails console我得到:

User.count
=> 2182

Profile.count
=> 2182

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

更新2

在应用程序中,真实用户(由“个人档案”表中的信息定义)可以使用许多电子邮件(个人,专业,...)来访问应用程序。 在这种情况下,模型如下所示:

class User < ActiveRecord::Base
  belongs_to :profile
end

class Profile < ActiveRecord::Base
  has_many :users
end

这就是为什么在Users表中有一个profile_id (在迁移过程中未更新的属性?)

我认为如果使用以下关联,则应使用user_id而不是profile_id

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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