2

それらの「私は明らかに何か間違ったことをしている」瞬間の1つを持っています。基本的なことをやろうとしていて、フレームワークと戦っているような気がするので、助けを求めています!

Rails 3を使用していますが、クリーンなURLのページを表示する検索フォームを作成する方法について少し混乱しています。

私のアプリケーションでは、任意の場所から別の場所へのルートから検索できます。

たとえば、有効なURLは/ routers / A / to /B/または/routes/Bになります。

私のroutes.rb:

match 'routes/:from/to/:to' => 'finder#find', :as => :find
match 'routes/find' => 'finder#find'

私の検索フォーム:

<% 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 %>

コントローラ:

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

で使用する:method => 'get'form_tag、アプリケーションは機能しますが、URLは恐ろしいものです。そしてもちろん、を使用する:method => 'post'と、変数は表示されなくなります。これはブックマークに適していません。フォームをPOSTした後、きれいなURLを使用するようにRailsに指示するにはどうすればよいですか?

私はRailsで非常に新しいので、あなたの忍耐に感謝します。

4

1 に答える 1

5

ルートには、。と入力すると表示される名前付きの自動パスが与えられますrake routes。例えば:

new_flag GET    /flags/new(.:format)      {:action=>"new", :controller=>"flags"}

new_flag_pathまたはを使用してパスを参照できますnew_flag_url

あなたのform_tagエントリはちょっと厄介です。別のメソッドを使用する代わりに、そのメソッドfindを使用することもできますがindex、それはあなたの選択です。

redirect_to標準を使用して、入力に基づいてよりきれいなURLにリダイレクトする方が簡単な場合があります。リダイレクトが必要ない場合は、jQueryを使用してフォームのアクションメソッドを動的に変更する必要があります。検索では通常、醜いGETパラメータを使用します。

したがって、コードを次のように変更します。

ルート.rb

get 'routes/:from/to/:to' => 'finder#routes', :as => :find_from_to
post 'routes/find' => 'finder#find', :as => :find

_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 %>

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
于 2011-08-07T04:25:22.797 に答える