Shiva
Shiva

Reputation: 12514

Ruby on Rails : is multiple respond_to block good in an action : best practice

I need to do condition check whether to render this or that. Is it good to wrap condition checks with respond_to block? like

   respond_to do |format|
     if @applicant.user_id.nil?
       # Some logic
       format.js
       format.html { redirect_to applicant_path(params[:id]) }
     else
       format.json { render json: {message: t('_applicants.flash.applicant_already_assigned')}, status: 400 }
     end
   end

or

I shall have multiple respond_to block inside if..else like

if @applicant.user_id.nil?
  # Some logic
  respond_to do |format|
    format.js
    format.html { redirect_to applicant_path(params[:id]) }
  end
else
  respond_to do |format|
    format.json { render json: {message: t('_applicants.flash.applicant_already_assigned')}, status: 400 }
  end
end

What would be the recommended best approach?

Upvotes: 1

Views: 1834

Answers (1)

Hristo Georgiev
Hristo Georgiev

Reputation: 2519

That's a lot of code for a controller action in my opinion. Rails was built with the DRY methodology in mind, so you can try something like this:

if you put this:

class SomeController < ApplicationController
  respond_to :html, :json , :js

In the beginning of your controller, you can make your actions much slimmer:

def someaction
 if aplicant.id.nil?
  redirect_to applicant_path(params[:id])
 end
 else
    flash[:notice] = "Applicant already assigned" 
 end
end 

Read more about rails responses in this article.

To directly answer your question: The first option with the single respond_to block is more reasonable because it involves writing less code. As I mentioned earlier, Rails is all about avoiding repetition, and two response blocks in a conditional operator are against the style of writing Rails apps.

Upvotes: 1

Related Questions