Controller code with exception handling 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
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 =&gt; :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.