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.
CodePudding user response:
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:
get '/search' => 'posts#search', as: 'search_post'
I edited the url of my form:
<%= form_with url: "/search", method: :get, class: 'nav-link' do |form| %>
<%= form.text_field :search %>
<%= form.submit "search" %>
<% end %>
The above passes the form input to the controller as params[:search], given that I set the form.text_field name attribute to :search.
CodePudding user response:
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:
<%= form_tag { action: "search", controller: "posts" }, { class: "nav-link" } do %>