2014-08-27 21 views
0
創建現有設計的用戶配置文件對象

我剛剛創建的屬性,如名稱,網站,生物爲我設計的用戶配置文件的模型。一切都很正常,但在Heroku上,我有100多個用戶了,所以這是相當繁瑣1.創建一個新的配置文件,2.將其分配給現有的用戶3.保存,所有在控制檯中。在Heroku

我不熟悉你可以在Heroku控制檯中做什麼,如果這甚至可能 - 但是我可以爲每個現有用戶(還沒有配置文件)批量創建100個新的配置文件。

眼下,有資料信息的任何視圖(即user.profile.name)是給我一個錯誤 - 我寧願創建一個空白的配置文件不是強迫用戶創建的界面一個新的。

的Rails 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 

profile.rb

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

belongs_to :user 

回答

0

我創建lib下/任務的文件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 

這是我從與控制檯運行:耙add_profile_to_users

這個工作,應該工作在Heroku上也是如此。

1

若要在Heroku上軌控制檯:

heroku run rails console 

另一種解決辦法是創造一個mi格雷申CreateProfileForUsers並遷移它放在你的PROD您部署:

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

def down 
end 

編輯

我剛剛得知,這是一個不好的做法,使用遷移這個!這是更好地創建構建您的個人資料rake任務,並儘快部署運行它。

+0

您可能需要使用user.save取決於如何建立您的build_profile。 – Mkou 2014-08-27 21:01:23

+0

我確實包括user.save - 沒有意識到遷移可能會被用於此,而使得這麼多的意義。謝謝!! – 2014-08-27 23:40:25

+0

謝謝!我最終寫了一個耙子任務。我會在一個單獨的答案中添加它。 – 2014-12-25 20:44:26