我在将 form_with 帮助程序连接到特定操作时遇到问题。我想搜索我的帖子,因此在 posts_controller 中创建了一个搜索操作。该逻辑正在工作(通过手动在 url 中输入请求进行测试),但我无法从搜索表单的提交按钮执行所述逻辑。
这是路由文件中的路由:
get '/posts/:search/search' => 'posts#search', as: 'search_post'
在 url 中提交 'localhost:3000/posts/1/search'
确实会返回我想要的页面和内容,但我希望能够输入 '1 ' 进入当前正在呈现但未提交的搜索栏。
以下是表单的代码:
<%= form_with url: "/:search/search", method: :get, class: 'nav-link' do |form| %>
<%= form.text_field :search %>
<%= form.submit "search" %>
<% end %>
当我输入 URL 模式时,路由和操作确实可以正常工作。返回搜索视图并显示正确的结果。我只是真的不明白如何将 form_with
连接到没有模型的操作。
我已经尝试了 form_with 帮助器的各种不正确的变体。我尝试使用 url: '/:search/search'
添加路径前缀,添加不正确的 @search
实例...我知道这些不会工作,我此时一直在尝试任何事情。
I'm having trouble connecting a form_with helper to a specific action. I want to search through my posts and so have created a search action in the posts_controller. The logic is working (tested by typing in the request in the url manually) but I can't execute said logic from the search form's submit button.
Here is the route in the routes file:
get '/posts/:search/search' => 'posts#search', as: 'search_post'
Submitting 'localhost:3000/posts/1/search'
in the url does return the page and content I want, but I want to be able to type '1' into a search bar that is currently rendering but not submitting.
Here is the code for the form:
<%= form_with url: "/:search/search", method: :get, class: 'nav-link' do |form| %>
<%= form.text_field :search %>
<%= form.submit "search" %>
<% end %>
The route and action DO work properly when I type in the URL pattern. The search view is returned with the proper results. I'm just really not understanding how to connect form_with
to an action without a model.
I've tried all sorts of incorrect variations for the form_with helper. I've tried adding the path prefix, using url: '/:search/search'
, adding an incorrect @search
instance... I know that these won't work, I've just been trying anything at this point.
发布评论
评论(2)
我想通了!
我缺少的是对表单输入字段上的“名称”属性的理解。我试图将“:search”(这是我表单中 name 属性的值)集成到导致我的搜索操作的路由中,但不知道 name 属性默认发送到它所在的控制器操作发送。
我将路线更改为:
我编辑了表单的 url:
上面将表单输入作为 params[:search] 传递到控制器,假设我将 form.text_field name 属性设置为 :search。
I figured it out!
What I was missing was the understanding of the "name" attribute on the input field of a form. I was attempting to integrate ":search" (which is the value of the name attribute in my form) in the route that lead to my search action, not knowing that the name attribute is sent by default to the controller action to which it is sent.
I changed my route to:
I edited the url of my form:
The above passes the form input to the controller as params[:search], given that I set the form.text_field name attribute to :search.
您可以通过使用
form_tag
。由于第一个参数接受了一个URL选项的哈希,因此Rails(应)将其映射到正确的路线:
You can directly map a form to a Rails controller and action by using
form_tag
.Since the first argument accepts a hash of url options, Rails will (should) map this to the correct route: