Just wondering what the accepted convention is for Rails controller design. Currently, every controller in my app that I've written it set up to send a JSON response when necessary. Thing is, I only ever utilse HTML responses in my app. So is it a good idea to have them defined?
For example:
def show
@dog = Dog.find(params[:id])
respond_to do |format|
format.html
format.json { render json: @dog } # needed?
end
end
It makes the controller code less readable (because more LOC) and it also means I have to think deeply about what a good JSON response should be when HTML is not being is used, so it decreases the speed of my controller development. This is especially true when you have conditional responses.
For example:
def create
@dog = Dog.new(params[:dog])
respond_to do |format|
if @dog.save
format.html { redirect_to @dog }
format.json { render json: @dog, status: :created, location: @dog }
else
format.html { render action: "new" }
format.json { render json: @dog.errors, status: :unprocessable_entity }
end
end
end
The only positive I can see is that it "future-proofs" the controllers (i.e. if I need JSON responses later on then they are already written).
But if I'm writing JSON responses just because then by that same logic I might as well write XML responses (i.e. format.xml
) too...