我创建了一个在模态窗口中不显示时效果很好的表单。当我将其插入模态时,突然POST正在寻找错误位置的路径。
我已经搜索了有关SO的问题,并通过RAILS指南和API文档阅读路由和控制器,但无法找到答案。我很想责怪":remote =>真"在表单中 - 似乎可能有一些东西需要添加到控制器 - 但我找不到。
以下是来自控制器佣金路线的路线:
messages POST /messages(.:format) messages#create
new_message GET /messages/new(.:format) messages#new
routes.rb中:
resources :messages, only: [:new, :create]
控制器:
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_for(:message, :remote => true) do |form| %>
来自导航:
<%= link_to('Contact', new_message_path, :class => 'contact', :remote => true, 'data-toggle' => "modal", 'data-target' => '#myModal') %>
日志中的POST错误:
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:
Started POST "/messages" for 127.0.0.1 at 2013-12-12 14:27:50 -0800
Processing by MessagesController#create as HTML
点击日期文件条目&#34;联系&#34;:
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)
让POST工作的正确方法是什么?
答案 0 :(得分:1)
您的form_for
标记希望将新的Message
对象传递给它。您已经在控制器的@message
操作中实例化了new
变量,因此只需将其传递到您的form_for
代码:
<%= form_for(@message, :remote => true) do |form| %>
答案 1 :(得分:0)
编辑:忽略......
/messages/new
仅适用于GET
个请求;这就是您的POST
请求失败的原因。尝试
<%= link_to('Contact', new_message_path, :class => 'contact', :method => :get, :remote => true, 'data-toggle' => "modal", 'data-target' => '#myModal') %>