module BasicCrud
Constants
- VERSION
Public Instance Methods
create() { || ... }
click to toggle source
# File lib/basic_crud.rb, line 36 def create @record = model.new(restricted_params) @notice = "#{model} was successfully created." yield if block_given? respond_to do |format| if @record.save format.html { redirect_to action: :index, notice: @notice } format.json { render @record, status: :created } else format.html { render :new } format.json { render json: @record.errors, status: :unprocessable_entity } end end end
destroy() { || ... }
click to toggle source
# File lib/basic_crud.rb, line 69 def destroy @record = fetch_record_by_param @notice = "#{model} was successfully destroyed." yield if block_given? @record.destroy respond_to do |format| format.html { redirect_to action: :index, notice: @notice } format.json { head :no_content } end end
edit() { || ... }
click to toggle source
# File lib/basic_crud.rb, line 26 def edit @record = fetch_record_by_param yield if block_given? end
fetch_record_by_param()
click to toggle source
default record by id for show, edit, ..
# File lib/basic_crud.rb, line 83 def fetch_record_by_param model.find(params[:id]) end
index() { || ... }
click to toggle source
# File lib/basic_crud.rb, line 4 def index @records = model.all yield if block_given? respond_to do |format| format.html { render :index } format.json { render json: @records } end end
model()
click to toggle source
Derive model from ControllerClass (ThingsController => Thing)
# File lib/basic_crud.rb, line 88 def model self.controller_name.classify.constantize end
new() { || ... }
click to toggle source
# File lib/basic_crud.rb, line 31 def new @record = model.new yield if block_given? end
restricted_params()
click to toggle source
Override this method to allow model attributes
# File lib/basic_crud.rb, line 93 def restricted_params #params.require(self.controller_name.classify.underscore.to_sym).permit([]) raise("No strong params set, override restricted_params method in your controller. E.g. params.require(:model).permit(:attribute1, :attribute2)") end
show() { || ... }
click to toggle source
# File lib/basic_crud.rb, line 15 def show @record = fetch_record_by_param yield if block_given? respond_to do |format| format.html { render :show } format.json { render json: @record } end end
update() { || ... }
click to toggle source
# File lib/basic_crud.rb, line 52 def update @record = fetch_record_by_param @notice = "#{model} was successfully updated." yield if block_given? respond_to do |format| if @record.update(restricted_params) format.html { redirect_to @record, notice: @notice } format.json { render @record, status: :ok } else format.html { render :edit } format.json { render json: @record.errors, status: :unprocessable_entity } end end end