Ruby on rails 在迁移期间用值填充表并不完全有效
由于我的用户表很大,我决定将用户配置文件信息迁移到一个单独的表:Profiles。所以用户表只能使用Desive gem访问信息。配置文件可以有多个用户访问 为此,我创建了一个迁移文件,以便从Users表在Profiles表中写入新数据:Ruby on rails 在迁移期间用值填充表并不完全有效,ruby-on-rails,migration,Ruby On Rails,Migration,由于我的用户表很大,我决定将用户配置文件信息迁移到一个单独的表:Profiles。所以用户表只能使用Desive gem访问信息。配置文件可以有多个用户访问 为此,我创建了一个迁移文件,以便从Users表在Profiles表中写入新数据: class MigrateSomeUsersInfoToProfilesTable < ActiveRecord::Migration def up puts "Pulling out profile information from Us
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
更新2
在应用程序中,由Profiles表中的信息定义的真实用户可以使用个人、专业人士等的许多电子邮件访问应用程序,。。。。在这种情况下,模型如下所示:
class User < ActiveRecord::Base
belongs_to :profile
end
class Profile < ActiveRecord::Base
has_many :users
end
这就是为什么在用户表属性中有一个配置文件id在迁移过程中没有更新???如果使用以下关联,我认为应该使用用户id而不是配置文件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
谢谢你的回答。事实上:User有一个:profile,profile有多个:users。这样,由其个人资料定义的唯一个人可以使用用户表中的许多电子邮件地址访问其帐户。这就是用户表具有profile_id属性的原因。我将更新问题。可能您应该使用has_和属于多个协会或has_多…:槽可以将profile.id放入if条件中吗?
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