How to stop controller execution after using redirect_to? (Using Rails)

I have a controller with several actions that take: year and: month as attributes from a URL. I made a private check_date method to check the date and check the date in the future.

def check_date(year, month) if month < 1 || month > 12 || year < 2000 flash[:notice] = I18n.t 'archive.invalid_date' redirect_to :action => 'index' elsif year > Date.today.year || (year == Date.today.year && month > Date.today.month) flash[:notice] = I18n.t 'archive.no_future' redirect_to :action => 'month_index', :year => Date.today.year, :month => Date.today.month, :type => params[:type] end end 

Is there a rail to complete controller execution after redirect_to?

The ways I can think of is to either throw an exception after redirect_to, or return a value from check_date and check it in every action that calls it - something like

 def month_index year = params[:year].to_i month = params[:month].to_i if !check_date(year, month) return ... end 

But I wonder if there are any good rails. I was half hoping that by calling the redirect_to rails, I find out that I want to stop, but this does not seem to be happening.

+44
ruby-on-rails error-handling
May 04 '09 at 16:21
source share
5 answers

You might want to use filters.

If you call your check_date as before_filter in the controller, the fact that it is displayed or redirected will not allow the controller to ever call the action method. It ends right there.

+35
May 04 '09 at 16:46
source share

You can also do:

 return redirect_to :action => 'index' 

and

 return redirect_to :action => 'month_index', :year => Date.today.year, :month => Date.today.month, :type => params[:type] 

because it looks better than returning to your line (IMHO).

+47
Nov 18 '09 at 0:40
source share

You can quit

 return false 

wherever you stop code execution in your action

+16
May 04 '09 at 17:40
source share

redirect_to just shows the rails what to do when it ends. Rails will get confused if you add other render or redirect_to directives after what you really want, so just return from the controller after redirecting to - this is a β€œnormal” rail to do something.

+6
May 4 '09 at 16:39
source share

I think the OP got confused in the redirect_to function.

redirect_to will be redirected at the end of the action. However, the rest of the controller function will be executed as usual. All you have to do (as published by other people) is to enable return like any other function call.

0
Dec 14 '15 at 18:23
source share



All Articles