Deborah
Deborah

Reputation: 4575

Rails can't find POST path for modal form

I've created a form that works great when it is not showing in a modal window. When I plug it into the modal, suddenly POST is looking for the path in the wrong place.

I've scoured questions on SO and read through the RAILS guides and API docs for routing and controllers, and can't find the answer. I'm tempted to blame ":remote => true" in the form - it seems like there may be something I need to add to the controller - but I can't find what.

Here are the routes from the controller's rake routes:

messages POST /messages(.:format)     messages#create
new_message GET  /messages/new(.:format) messages#new

routes.rb:

resources :messages, only: [:new, :create]

Controller:

class MessagesController < ApplicationController

  def new
    @message = Message.new
  end

  def create
    @message = Message.new(params[:message])
      if @message.valid?
        NotificationsMailer.new_message(@message).deliver
        redirect_to root_path, :notice => "Thanks! Your message was sent."
        return  
      else
        render :new
      end
  end
end

Form tag (the form displays and works beautifully except for sending):

<%= form_for(:message, :remote => true) do |form| %>

From the Nav:

<%= link_to('Contact', new_message_path, :class => 'contact', :remote => true, 'data-toggle' => "modal", 'data-target' => '#myModal')  %>

POST error from the log:

Started POST "/messages/new" for 127.0.0.1 at 2013-12-12 14:33:43 -0800
ActionController::RoutingError (No route matches [POST] "/messages/new"):

POST as it happens in the working, non-modal version:

Started POST "/messages" for 127.0.0.1 at 2013-12-12 14:27:50 -0800
Processing by MessagesController#create as HTML

Log file entry from click on "Contact":

Started GET "/messages/new" for 127.0.0.1 at 2013-12-12 14:33:37 -0800
Processing by MessagesController#new as JS
  Rendered messages/_form.erb (5.1ms)
  Rendered messages/_new.erb (7.7ms)
  Rendered messages/new.js.erb (10.7ms)
Completed 200 OK in 17ms (Views: 14.2ms | ActiveRecord: 0.0ms)

What is the right thing to do to get the POST working?

Upvotes: 0

Views: 1145

Answers (2)

zeantsoi
zeantsoi

Reputation: 26193

Your form_for tag is expecting a new Message object to be passed to it. You've already instantiated a @message variable in the new action of your controller, so simply pass it to your form_for tag:

<%= form_for(@message, :remote => true) do |form| %>

Upvotes: 1

janfoeh
janfoeh

Reputation: 10328

Edit: disregard that…

/messages/new is only available to GET requests; this is why your POST request fails. Try

<%= link_to('Contact', new_message_path, :class => 'contact', :method => :get, :remote => true, 'data-toggle' => "modal", 'data-target' => '#myModal')  %>

Upvotes: 0

Related Questions