Rails POST表单到漂亮的URL

tkr*_*car 2 routes rails-routing ruby-on-rails-3

其中一个'我显然做错了'的时刻.感觉就像我正在尝试做一些基本的事情,并与框架作斗争,所以我很有吸引力!

我正在使用Rails 3,并且对于如何创建一个导致页面包含干净URL的搜索表单感到有些困惑.

我的应用程序允许您从任何位置的路线搜索到另一个位置.

例如,有效的URL将是/ routes/A/to/B /或/ routes/B.

我的routes.rb:

match 'routes/:from/to/:to' => 'finder#find', :as => :find
match 'routes/find' => 'finder#find'
Run Code Online (Sandbox Code Playgroud)

我的搜索表单:

<% form_tag('/routes, :method => 'post') do %>
  <%= label_tag(:from, "From:") %>
  <%= text_field_tag(:from) %>
  <%= label_tag(:to, "To:") %>
  <%= text_field_tag(:to) %>
  <%= submit_tag("Go") %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

控制器:

class FinderController < ApplicationController
  def index
  end

  def find
    if params[:from].blank? or params[:to].blank?
      render :action => "invalid_results" and return
    end
    @from = Location.find_by_code(params[:from].upcase)
    @to = Location.find_by_code(params[:to].upcase)
    if @from.nil? or @to.nil?
      render :action => "invalid_results" and return
    end

    @routes = Route.find_all_by_from_location_id_and_to_location_id(@from, @to)

  end
end
Run Code Online (Sandbox Code Playgroud)

当我:method => 'get'在我form_tag的应用程序中使用时,该应用程序可以工作,但URL很可怕.而且,当然,:method => 'post'变量不再可见,这对书签来说是不好的.在POST表单后如何告诉Rails使用我漂亮的URL?

我在Rails非常新,所以请耐心等待.

Dex*_*Dex 5

您的路由将获得一个自动命名路径,您可以通过键入来查看rake routes.例如:

new_flag GET    /flags/new(.:format)      {:action=>"new", :controller=>"flags"}
Run Code Online (Sandbox Code Playgroud)

您可以使用new_flag_path或引用路径new_flag_url

你的form_tag参赛作品有点棘手.find您也可以使用该index方法,而不是使用单独的方法,但这是您的选择.

您可能会发现使用标准更容易redirect_to根据输入重定向到更漂亮的URL.如果您不想重定向,那么您将需要使用jQuery动态更改表单的操作方法.搜索通常使用丑陋的GET参数.

所以我会改变你的代码看起来像这样:

的routes.rb

get 'routes/:from/to/:to' => 'finder#routes', :as => :find_from_to
post 'routes/find' => 'finder#find', :as => :find
Run Code Online (Sandbox Code Playgroud)

_form.html.erb

<% form_tag find_path, :method => :post do %>
  <%= label_tag(:from, "From:") %>
  <%= text_field_tag(:from) %>
  <%= label_tag(:to, "To:") %>
  <%= text_field_tag(:to) %>
  <%= submit_tag("Go") %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

finder_controller.rb

class FinderController < ApplicationController
  def index
  end

  def find
    if params[:from].blank? or params[:to].blank?
      render :action => "invalid_results" and return
    end
    @from = Location.find_by_code(params[:from].upcase)
    @to = Location.find_by_code(params[:to].upcase)
    if @from.nil? or @to.nil?
      render :action => "invalid_results" and return
    end

    redirect_to find_from_to_path(@from, @to)

  end

  def routes
     @routes = Route.find_all_by_from_location_id_and_to_location_id(params[:from], params[:to])
  end
end
Run Code Online (Sandbox Code Playgroud)