Skip to content

Instantly share code, notes, and snippets.

@rahulnyk
Created August 10, 2020 15:05
Show Gist options
  • Save rahulnyk/4bdbca09b80baf818b3f7ebda42376bc to your computer and use it in GitHub Desktop.
Save rahulnyk/4bdbca09b80baf818b3f7ebda42376bc to your computer and use it in GitHub Desktop.
A Ruby on Rails controller concern which adds basic CRUD operations for any model.
# frozen_string_literal: true
# Controller concern for basic crud.
# Can be added to any controller like so
# include Crud
# Assumptions:
# 1. Model class defines a constant called WHITELIST_FIELDS
# as an array of symbols for attributed that are allowed for creating a record.
# 2. Model is serialized elsewhwere. This can be done either by overwriting as_json
# method in the model class, or by using separate serializers. By default as_json
# will render all the model attributes.
module Crud
extend ActiveSupport::Concern
included do
# guess the model name from the controller name
# eg. if the controller is users_controller, modelname will be User
def model_class_const
controller_name.singularize.capitalize.constantize
end
# create a sumbol for the model name
def model_class_symbol
model_class_const.to_s.downcase.to_sym
end
# List records
def index
render_records
end
# Create record
def create
@record = model_class_const.create! record_params
render_record message: "#{model_class_const.to_s} created"
end
# Delete record
def delete
record.destroy
render_record message: "#{model_class_const.to_s} deleted"
end
private
# Find record using params[:id]
def record
@record ||= model_class_const.find(params[:id])
end
# Find all records. You can also paginate them here if you like.
def records
@records ||= model_class_const.order(created_at: :desc, updated_at: :desc)
end
# Render one record
def render_record(**opts)
render json: {
record: record.as_json
}.merge(opts)
end
# Render array of records
def render_records(**opts)
render json: {
records: records.as_json
}.merge(opts)
end
# Strong params.
# Note: this assumes that the WHITELIST_FIELDS is an array of symbols defined
# in the model class. eg. User model may have
# WHITELIST_FIELDS = %i[name email]
def record_params
params.require(model_class_symbol).permit(model_class_const::WHITELIST_FIELDS)
end
end
end
@enliven-
Copy link

Pretty cool stuff!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment