Skip to content

Instantly share code, notes, and snippets.

@tannakartikey
Created August 15, 2023 18:31
Show Gist options
  • Save tannakartikey/b35522f9e99b63b20423ee717cad3cf6 to your computer and use it in GitHub Desktop.
Save tannakartikey/b35522f9e99b63b20423ee717cad3cf6 to your computer and use it in GitHub Desktop.
Validate and create or import multiple records in Rails
# app/models/learner_collection.rb
class LearnerCollection
include ActiveModel::Model
attr_accessor :learners, :current_user
def initialize(learners_attributes: [], **kw_args)
super
end
def learners_attributes=(attrs)
self.learners = attrs.map do |learner_attrs|
learner = Learner.new(learner_attrs)
learner.organization = current_user.find_organization
learner
end
end
def valid?
errors.clear
if learners.reject(&:valid?).any?
learners.map do |u|
errors.add(:base, u.errors.full_messages)
end
end
errors.none?
end
def save!
raise(ActiveRecord::RecordInvalid) && return unless valid?
save_in_transaction
end
def save
return false unless valid?
save_in_transaction
end
def send_invites
learners.map(&:send_invite)
end
private
def save_in_transaction
Learner.transaction do
learners.reject(&:save!).none?
end
end
end
#app/controllers/learners_controller.rb
class LearnersController < ApplicationController
def create
@collection = LearnerCollection.new(
learners_attributes: learner_params.require(:learners),
current_user: current_user
)
if @collection.save
render json: @collection.learners, status: :created
else
render json: @collection.errors.full_messages, status: :unprocessable_entity
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment