簡體   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