Skip to content

Instantly share code, notes, and snippets.

@ArmandoAssuncao
Last active March 14, 2020 18:08
Show Gist options
  • Save ArmandoAssuncao/0e73cf2b5c29090d4c79c8efbc97df9d to your computer and use it in GitHub Desktop.
Save ArmandoAssuncao/0e73cf2b5c29090d4c79c8efbc97df9d to your computer and use it in GitHub Desktop.
validates model when uses function mongo insert_many
# model Game
class Game
include Mongoid::Document
include Mongoid::Timestamps
attr_accessor :skip_uniqueness_validations
attr_readonly :skip_uniqueness_validations
field :game_name, type: String
field :game_id, type: String
belongs_to :user, class_name: 'User', required: false
# skip validation of uniqueness to model User
validates_presence_of :user, unless: :skip_uniqueness_validations
validates_presence_of :user_id
validates :game_name, presence: true, allow_nil: true
validates :game_id, presence: true
# How method "valid?" makes a query find to Mongo to check if field is unique,
# this validations must be skipped for that not make requests to Mongo.
validates_uniqueness_of :game_id, unless: :skip_uniqueness_validations
validates_uniqueness_of :game_name, unless: :skip_uniqueness_validations
end
class InsertManyWithValidations
user = User.first
games = [
{ game_id: '1', name: 'Halo' },
{ game_id: '2', name: 'GoW' },
{ game_id: '2', name: 'KF' },
]
games = games.map do |game|
game_model = Game.new(
user_id: user.id,
game_id: game[:game_id],
game_name: game[:name],
skip_uniqueness_validations: true # no validates uniqueness (improves performance)
)
game_model.set_created_at # add created_at and updated_at
# method "valid?" will run all validations, except uniqueness
raise ModelInvalidError unless game_model.valid?
game_hash = HashWithIndifferentAccess[game_model.attributes]
game_hash.symbolize_keys.except(:_id)
end
Game.collection.insert_many(games)
rescue ServiceInvalidError => e
puts e.message
puts e.backtrace[0..5]
# run rollback
end
class ModelInvalidError < StandardError; end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment