Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use custom route upon model validation failure

I've just added a contact form to my Rails application so that site visitors can send me a message. The application has a Message resource and I've defined this custom route to make the URL nicer and more obvious:

map.contact '/contact', :controller => 'messages', :action => 'new'

How can I keep the URL as /contact when the model fails validation? At the moment the URL changes to /messages upon validation failure.

This is the create method in my messages_controller:

def create
  @message = Message.new(params[:message])

  if @message.save
    flash[:notice] = 'Thanks for your message etc...'
    redirect_to contact_path
  else
    render 'new', :layout => 'contact'
  end
end

Thanks in advance.

like image 743
John Topley Avatar asked Jan 24 '23 11:01

John Topley


1 Answers

I just came up with a second solution, guided by Omar's comments on my first one.

If you write this as your resources route

map.resources :messages, :as => 'contact'

This gives (amongst others) the following routes

/contact # + GET = controller:messages action:index
/contact # + POST = controller:messages action:create

So when you move your 'new' action code into your 'index' action, you will have the same result. No flicker and an easier to read routes file. However, your controller will make no more sense.

I, however, think it is a worse solution because you'll soon forget why you put your 'new' code into the index action.

Btw. If you want to keep a kind of index action, you could do this

map.resources :messages, :as => 'contact', :collection => { :manage => :get }

This will give you the following route

manage_messages_path # = /contact/manage controller:messages action:manage

You could then move your index action code into the manage action.

like image 82
Pieter Jongsma Avatar answered Jan 26 '23 05:01

Pieter Jongsma