ruby on rails - Insert data in migration if it does not exist -
i have following migration:
sequel.migration create_table :user_settings primary_key :id string :signature, null: true, text: true end alter_table :user_settings add_foreign_key :user_id, :users, null: false, on_delete: :cascade add_index :user_id end end down drop_table :user_settings end end
this add default user settings.
the problem have want create row in user_settings table every user in database not have row, prior migration.
i want check if each user has row a matching user_id in database , if not, want insert default values.
how can in migration?
normally, kind of things done using rake task need in migration. guess have added association in user , usersetting model , has_one association. need create new migration file
def users = user.includes([:user_setting]).where(:user_setting => {:user_id => nil}) users.each |user| user.create_user_setting # or can write # usersetting.create({:user_id => user.id, :signature => 'your-custom-text'}) end end
Comments
Post a Comment