传递参数来形成 [英] Passing parameter to form
问题描述
我有这样的路线:
match'/:search /:page',:to => 'search#create'
以我的形式显示:
<%= form_for:search,:url => {:控制器=> 'search',:action => 'create',:page => 1,:search => ???} do | f | %GT;
我需要将一些内容传递给:search
但我希望它是与表单一起提交的值。我该怎么办?
有没有直接的方式做到这一点,因为表单与url(动作)必须呈现在用户输入任何内容到搜索中所以你需要初始值,但是当你不知道用户想要输入什么时可能没有意义。使用参数GET表单可以解决这个问题,但我想你需要很好的搜索URL。
通常有两种选择:
-
您无法通过简单表单提交更改网址路径 - 只可以添加参数(?x = 1& y = 2 ...)。但是,当用户输入内容搜索输入(onchange)或提交表单(onsubmit)时,您可以通过JavaScript修改整个URL。形成输入值,然后将其重定向到正确的URL。例如。
/ searchforward?search = Query& page = 1
应该转发给/ Query / 1
。
routes.rb:
匹配'searchforward',:to => 'search#searchforward'
match'/:search /:page,:to => 'search#create',:as => :search
控制器:
def searchforward
redirect_to search_path(params [:search],params [:page]
end
I have a route like this:
match '/:search/:page', :to => 'search#create'
and in my form:
<%= form_for :search, :url => {:controller => 'search', :action => 'create', :page => 1, :search => ???} do |f| %>
I need to pass something to :search
but I want it to be the value that is submitted with the form. What do I do?
There is no straight way to do that as form with url (action) must be rendered before user types anything into search. So you need initial value, but it may not make sense when you don't know what user wants to type in. GET form with parameters would solve it but I suppose you want "nice" search urls.
Generally there are two options:
You can't change URL path by simple form submittion - only params (?x=1&y=2...) may be added. But you can modify whole URL by JavaScript when user types something to search input (onchange) or submits form (onsubmit).
Use another action which will receive standard form input values then redirect it to proper url. E.g.
/searchforward?search=Query&page=1
should forward to/Query/1
.
routes.rb:
match 'searchforward', :to => 'search#searchforward'
match '/:search/:page, :to => 'search#create', :as => :search
controller:
def searchforward
redirect_to search_path(params[:search],params[:page]
end
这篇关于传递参数来形成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!