【问题标题】:Create a Profile object for existing Devise Users on Heroku为 Heroku 上的现有设计用户创建 Profile 对象
【发布时间】:2014-10-21 14:14:29
【问题描述】:

我刚刚为我的 Devise 用户创建了名称、网站、简历等属性的 Profile 模型。一切都很好,除了在 Heroku 上,我已经有 100 多个用户,所以 1. 创建一个新的配置文件,2. 将其分配给现有用户 3. 保存,所有这些都在控制台中相当乏味。

我不熟悉您可以在 Heroku 控制台中执行的操作以及是否可以执行此操作 - 但我可以为每个现有用户(还没有配置文件)批量创建 100 多个新配置文件。

现在,任何包含个人资料信息(即 user.profile.name)的视图都会给我一个错误——我宁愿创建一个空白个人资料也不愿强制用户在界面中创建一个新个人资料。

Rails 3.2.12

用户.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

profile.rb

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

belongs_to :user

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 heroku devise


    【解决方案1】:

    在 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 任务来构建您的配置文件并在部署后立即运行它。

    【讨论】:

    • 您可能需要使用 user.save,具体取决于您的 build_profile 的创建方式。
    • 我确实包含了 user.save - 没有意识到迁移可以用于此,但非常有意义。谢谢!!
    • 谢谢!我确实最终写了一个 rake 任务。我将在单独的答案中添加它。
    【解决方案2】:

    我在 lib/tasks 下创建了一个 add_profile_to_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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多