使用带有参数和form_tag的命名路由 [英] Using named routes with parameters and form_tag
问题描述
我正在尝试在Rails中创建一个简单的搜索表单,但是我想我缺少了一些东西.
I'm trying to create a simple search form in Rails, but I think I'm missing something.
我有一个搜索的命名路线:
I have a named route for search:
map.search ":first_name/:last_name", :controller => "home", :action => "search"
我正在尝试在搜索表单中使用它:
I'm trying to use that in my search form:
<% form_tag(search_path, :method => 'get') do %>
<%= text_field_tag(:first_name) %>
<%= text_field_tag(:last_name) %>
<%= submit_tag("Search") %>
<% end %>
但是当我加载搜索表单时,我得到了一个ActionController :: RoutingError:
But when I load up the search form I get an ActionController::RoutingError:
search_url无法从{:action =>"search",:controller =>"home"}生成-您的路由可能不明确,或者可能需要为此路由提供其他参数. content_url具有以下必需参数:[:first_name,:last_name]-它们是否都满足?
search_url failed to generate from {:action=>"search", :controller=>"home"} - you may have ambiguous routes, or you may need to supply additional parameters for this route. content_url has the following required parameters: [:first_name, :last_name] - are they all satisfied?
我想念什么?我认为在表单中定义的字段会自动与我的路线参数链接起来. :-/
What am I missing? I thought the fields defined in my form would be automatically linked up with my route parameters. :-/
更新:
我了解到search_path是在现在显示表单之前生成的,因此无法更新.事后看来很明显!
I understand that search_path is generated before the form is displayed now, so it can't be updated. Obvious in hindsight!
我更改了路线:
map.search 'search', :controller => "home", :action => "search"
map.name ':first_name/:last_name', :controller => "home", :action => "name"
现在search
动作就可以了:
def search
redirect_to name_path(params)
end
一切正常!此处的主要目标是从名称命名路由中获取该URL,作为进行搜索的结果.谢谢大家!
It all works a treat! The main goal here was getting that URL from the name named route as result of doing a search. Thanks guys!
推荐答案
form_for
生成表单,并且必须指定创建search_path
所需的所有参数,因此它应类似于:
form_for
generates form and it has to have specified all parameters that are needed to create search_path
, so it should look like:
<% form_tag(search_path, :firstname => 'some_text', :lastname => 'some_text', :method => 'get') do %>
或至少类似这样的东西. HTML标记form
具有参数action='/some/url'
,这就是为什么必须为search_path
指定所有参数的原因.但是上面的示例无法按预期工作.
or at least something like this. HTML tag form
has parameter action='/some/url'
and that's why you have to specify all parameters for search_path
. But the above example won't work as you expected.
那你能做什么?
-
创建一个具有
action='/'
并使用js的空表单,然后再将其替换为输入文本字段的内容,然后再提交.
Create empty form that has
action='/'
and with js replace it with content of your input text fields before submitting.
在示例/search
上创建另一条路由,该路由从Submit检索参数,然后重定向到正确的路径.
Create another route, on example /search
that recives parameters from submit and then redirects to correct path.
可能还有一些更好的方法;)
Probably there is also some better ways to do it ;)
这篇关于使用带有参数和form_tag的命名路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!