Ruby on rails 为Heroku上的现有设备用户创建配置文件对象

Ruby on rails 为Heroku上的现有设备用户创建配置文件对象,ruby-on-rails,ruby-on-rails-3,heroku,devise,Ruby On Rails,Ruby On Rails 3,Heroku,Devise,我刚刚为我的Desive用户创建了一个属性(如姓名、网站、简历)的配置文件模型。一切都很好,除了在Heroku上,我已经有100多个用户了,所以1。创建一个新的配置文件,2。将其分配给现有用户3。保存,全部在控制台中 我不熟悉在Heroku控制台中可以做什么,如果这是可能的话——但是我可以为每个现有用户批量创建100多个新的配置文件(还没有配置文件) 现在,任何具有配置文件信息(即user.Profile.name)的视图都会给我一个错误——我宁愿创建一个空白配置文件,也不愿强制用户在界面中创建

我刚刚为我的Desive用户创建了一个属性(如姓名、网站、简历)的配置文件模型。一切都很好,除了在Heroku上,我已经有100多个用户了,所以1。创建一个新的配置文件,2。将其分配给现有用户3。保存,全部在控制台中

我不熟悉在Heroku控制台中可以做什么,如果这是可能的话——但是我可以为每个现有用户批量创建100多个新的配置文件(还没有配置文件)

现在,任何具有配置文件信息(即user.Profile.name)的视图都会给我一个错误——我宁愿创建一个空白配置文件,也不愿强制用户在界面中创建一个新的配置文件

轨道3.2.12

user.rb

class User < ActiveRecord::Base
after_create :build_profile
attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :role, :profile_attributes
has_one :profile, dependent: :destroy
accepts_nested_attributes_for :profile
class用户
profile.rb

class Profile < ActiveRecord::Base
attr_accessible :bio, :name, :website, :user_id

belongs_to :user
类配置文件
在heroku上安装rails控制台:

heroku run rails console
另一种解决方案可以是创建迁移CreateProfileForUsers,并在部署时在产品上进行迁移:

def up
  User.all.each do |user|
    if user.profile.nil?
       user.build_profile
    end
  end
end

def down
end
编辑


我刚刚了解到,使用迁移来实现这一点是一种不好的做法!最好创建一个rake任务来构建您的配置文件,并在部署后立即运行它。

我在lib/tasks下创建了一个文件add\u profile\u to\u users.rake:

task :add_profile_to_users => :environment do
    User.all.each do |u| #where no profile
        puts "Updating user id #{u.id}..."
            if u.profile.nil?
               u.build_profile
           else
                puts "skip"
            end
        puts "...#{u.name} has been updated!" if u.save
    end
end
我从控制台运行时使用了:rake add_profile_to_users


这在heroku上也起作用了,应该也起作用。

您可能需要使用user.save,具体取决于您的构建配置文件的创建方式。我确实包含了user.save-没有意识到迁移可以用于此,但非常有意义。非常感谢。谢谢我最终写了一个rake任务。我将在另一个答复中补充这一点。