Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a controller with multiple actions that take :year and :month as attributes from the URL. I have made a private method check_date to check the date is valid and check the date is not 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 rails way of ending controller execution after the redirect_to?

Ways I can think of are either to throw an exception after the redirect_to or to return a value from check_date and check it in each 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 is some nice rails way of doing this. I was half hoping that having called redirect_to rails would recognise I wanted to stop, but that doesn't seem to happen.

like image 254
Hamish Downer Avatar asked May 04 '09 16:05

Hamish Downer


People also ask

What does redirect_to return?

redirect_to will cause any automatic rendering to be skipped. You only need the 'return' if you need to bypass further code in the action. If the further code does an explicit render , then you must do a return to avoid an error of redirect and render both being present.

How do I redirect back in rails?

In Rails 4. x, for going back to previous page we use redirect_to :back. However sometimes we get ActionController::RedirectBackError exception when HTTP_REFERER is not present. This works well when HTTP_REFERER is present and it redirects to previous page.


1 Answers

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] 

since it looks nicer than putting return on its own line (IMHO).

like image 170
Slipp D. Thompson Avatar answered Oct 11 '22 12:10

Slipp D. Thompson