Ruby on Rails: How to redirect page based on post params in search_field?

时光总嘲笑我的痴心妄想 提交于 2019-12-02 03:53:43

In your main#company_post method, put the following:

redirect_to "/company/#{params[:symbol]}"

So the routes should be:

get  "/company/:symbol"  => "main#company"
post "/company"  => "main#company_post"

The controller:

def company_post
  redirect_to "/company/#{params[:symbol]}"
end

The view:

<%= form_tag("/company", method: :post) do %>
  <%= search_field_tag(:symbol, "Enter symbol") %>
  <%= submit_tag ("Search") %>
<% end %>

At the end of your #company controller method you probably will do something like this

render "#{params[:symbol]}"

or

render partial: "#{params[:symbol]}"

along with have a template file with the same name of the company, like google.html.erb

Give it a try!

I make simple search system that looks almost like your task

Full example

routes.rb

  post 'search'          => 'vids#prepare_search', as: :prepare_search_vids
  get  'search(/*query)' => 'vids#search',         as: :search_vids

vids_controller.rb

  # GET /search(/*query)
  def search
    @results = Title.search params[:query] if search_query?
    if @results.count == 1
      flash[:notice] = I18n.t 'vids.search.signle_result'
      redirect_to @results[0].vid
    end
    @query = params[:query]
  end

  # POST /search
  def prepare_search
    query = params[:q] ? params[:q] : ''
    redirect_to search_vids_path(query)
  end

  private

    def search_query?
      params[:query] and !params[:query].blank?
    end

Also in your situation I recommend use asteriks instead of colon in routes http://guides.rubyonrails.org/routing.html#route-globbing-and-wildcard-segments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!