HiveBrain v1.2.0
Get Started
← Back to all entries
debugrubyrailsMinor

Controller code with exception handling

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
handlingexceptionwithcontrollercode

Problem

I am writing this code in the controller. I want to know is this the right way to write it or not. Because I don't want to write If else conditions and then either redirect or render the pages.

Here is my sample code :

def create
    @stud = Student.new params[:student]
    @stud.save!
    redirect_to students_path(@stud)
  rescue
    render 'new'
end

Solution

I know you wanted to avoid if / else, but I think i would probably write it like this:

def create
  @stud = Student.new params[:student]

  if @stud.save
    redirect_to @stud
  else
    render :action => :new
  end
end


Which is the same amount of code but has two advantages:

-
it is more readable by a human. Rescue is not a human concept in logic, whereas if / else is clearly understood.

-
when you rescue here, you rescue from anything. if @stud.save is specific, if that fails it won't throw an exception, but will return false. So you are responding to the appropriate condition.

One other note: if you want to stick with the rescue pattern, you could shorten the function by a single line by writing

@stud = Student.create! params[:student]


which is the same as writing:

@stud = Student.new params[:student]
@stud.save!


ian.

Code Snippets

def create
  @stud = Student.new params[:student]

  if @stud.save
    redirect_to @stud
  else
    render :action => :new
  end
end
@stud = Student.create! params[:student]
@stud = Student.new params[:student]
@stud.save!

Context

StackExchange Code Review Q#10482, answer score: 3

Revisions (0)

No revisions yet.