我正在尝试构建一个表单,将数据发布到另一个 Controller /操作,然后重定向回另一个页面。
我的表单模板:
<%= form_for @url, :url => { :controller => "url", :action => "create" }, :html => {:method => :post} do |f| %>
<%= f.text_field :url, :placeholder => "http://" %>
<%= f.submit "Kürzen", :class => "btn" %>
<% end %>
我的 url_controller:
class UrlController < ApplicationController
def create
redirect_to shorturl_path
end
end
我的路线:
Ssurl::Application.routes.draw do
get 'shorturl' => 'landingpage#shorturl', :as => :shorturl
post '/url/create' => 'url#create'
root :to => 'landingpage#index', :as => :landingpage
end
当我提交表单时,页面使用表单的获取参数重新加载? 所以有2个错误:
- 表单使用 get 而不是 post?
- 重定向不起作用
怎么了?
最佳答案
看起来您正在尝试通过指定 Controller 和操作在 form_for
中生成 URL,但您并未在 routes.rb 中映射此路由。
所以你有两个选择。第一种是在 form_for
中“硬编码”URL,如下所示:
<%= form_for @url, :url => "/url/create", :html => {:method => :post} do |f| %>
但更好的解决方案是让您的路线成为 RESTful 形式。
你可以这样做:
Ssurl::Application.routes.draw do
get 'shorturl' => 'landingpage#shorturl', :as => :shorturl
resource :url, :only => [:create]
root :to => 'landingpage#index', :as => :landingpage
end
这将使用 POST http 方法创建一个 RESTful 创建路由。所以你的 form_for
看起来像这样:
<%= form_for @url do |f| %>
干净多了!
关于ruby-on-rails - 将数据从表单发布到不同的 Controller 并重定向回来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14379259/