I’m trying to build a form which posts data to another controller/action and then redirect back to another page.
My template with the form:
<%= 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 %>
My url_controller:
class UrlController < ApplicationController
def create
redirect_to shorturl_path
end
end
My route:
Ssurl::Application.routes.draw do
get 'shorturl' => 'landingpage#shorturl', :as => :shorturl
post '/url/create' => 'url#create'
root :to => 'landingpage#index', :as => :landingpage
end
When i submit the form, the page reload with the get parameters of the form?
So there are 2 errors:
- The form uses get instead of post?
- Redirect doesn’t work
What’s wrong?
It looks like you’re trying to generate a URL in your
form_forby specifying the controller and the action but you’re not mapping this route in your routes.rb.So you have two options. The first is to ‘hardcode’ the URL in the
form_for, like this:But a much better solution would be to get your routes into RESTful shape.
You could do this:
Which will create a RESTful create route using the POST http method. So your
form_forwould then look like this:Much cleaner!