Skip to content

Instantly share code, notes, and snippets.

task remove_duplicate_memberships: :envrionment do
# the sub query finds all duplicated memberships
# the outer query filters out any duplicates that except the one with the highest ID (per organization)
sql = <<-eos
select * from memeberships inner join
(select max(id) maxid, user_id, organization_id
from memberships
group by user_id, organization_id
having count(1) > 1) as keep
on (memberships.user_id = keep.user_id
users_missing_profiles =
User.joins("left outer join profiles on users.id = profiles.user_id").where("profiles.id is null")
users_missing_profiles.each(&:generate_profile)
# Which profile is returned?
user = User.first
# Deterministic
# SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
user.profile
# Non-deterministic! THERE IS NO ORDER CLAUSE!
# SELECT "profiles".* FROM "profiles" WHERE "profiles"."user_id" = $1 LIMIT 1
# add an index to speed up search for duplciates
task remove_invalid_profiles: :envrionment do
invalid_profiles = Profile.joins("left outer join users on profile.user_id = users.id")
.where("users.id is null")
invalid_profiles.destroy_all
end
class AddForeignKeyConstraintToProfile < ActiveRecord::Migration
def change
add_foreign_key :profiles, :users, on_delete: :cascade
task set_proper_timezone: :envrionment do
invalid_profiles = Profile.where("timezone is null or timezone not in (?)", ActiveSupport::TimeZone.zones_map.keys)
invalid_profiles.each(&:set_default_timezone)
end
class Profile < ActiveRecord::Base
validates :timezone, inclusion: { in: ActiveSupport::TimeZone.zones_map.keys }
end
task remove_invalid_users: :environment do
invalid_users = User.where("email is null or email is ''")
# Users without emails probably can't even log in so it's probably best to destroy the records
invalid_users.destroy_all
end
task set_default_locale: :envrionment do
invalid_profiles = Profile.where("locale is null or locale = ''")
class Organization < ActiveRecord::Base
has_many :memberships, dependant: :destroy
has_many :users, through: :memberships
end
class User < ActiveRecord::Base
has_many :profiles, dependant: :destroy
has_many :memberships, dependant: :destroy
has_many :organizations, through: :memberships
end
@wivarn
wivarn / invald_records.rake
Last active October 16, 2015 20:35
Scan the database for invalid records
HEADERS = [
"Recrod ID",
"Created At",
"Updated At",
"Error Messages"
]
def all_models
tables = ActiveRecord::Base.connection.tables.sort
tables.map { |name| name.classify.safe_constantize }.compact
@wivarn
wivarn / some_model.rb
Last active November 17, 2015 05:17
Attachment Validations
class SomeModel < ActiveRecord::Base
validates :index, length: { maximum: 25 }
end