I'm currently working on building a simple REST API using Ruby on Rails. I noticed that a lot of the things I did were a bit redundant, especially the models. Just to clarify: I want this to be a REST API which returns JSON, without any views (I want to be able to access it from different applications, mainly Apache Cordova). Within Cordova I wanted to use ReactJS.
Sadly, my Rails controllers all look like this:
class StudentsController < ApplicationController
def index
@students = Student.all
render json: @students
end
def create
if @student.present?
render nothing: true, status: :conflict
else
@student = Student.new(student_params)
if @student.save
render json: @student
else
render nothing: true, status: :bad_request
end
end
end
def show
@student = Student.find(params[:id])
render json: @student.classes
end
def update
@student = Student.find(params[:id])
@student.update(student_params)
if @student.save
render json: @student
else
render nothing: true, status: :bad_request
end
end
def delete
if Student.destroy(params[:id])
render nothing: true, status: :ok
else
render nothing: true, status: :bad_request
end
end
private
def student_params
params.permit(:first_name, :last_name, :grade_id)
end
end
I literally got three of them with only the classname changed. Is there a smarter way to organize this? I may have to change override some functions, but some functions will be identical.
I also have a few database relationships, for example grades and classes to teachers and students. Does anyone have some information about best practices for this? I seem to be creating a lot of "relationship" tables for these many-to-many relationships.
For the RoR Rest API Part I found this tutorial.