Reputation: 81
I have a form which contains some text_fields. One of them is the zip code field. It has a button "Search" that calls an specific action "search_zip_code" which returns the address values associated with that field. How can I invoke this action inside a form_for tag? I have already tried a form_tag nested to it, but the submit action invokes the :create method. If I use a "link_to", I can't pass the zip code entered by the user. What is the best approach for that?
<%= form_for(@model) do |m|%>
<%= m.label :field_1 %>
<%= m.text_field :field_1 %>
<%= m.label :field_2 %>
<%= m.text_field :field_2 %>
<div class="field">
<%= form_tag("/search_zip_code", method: "get") do %>
<%= label_tag(:zip, "ZIP Code:") %>
<%= text_field_tag(:zip) %>
<%= submit_tag("Search") %>
<% end %>
</div>
<%= m.submit %>
<% end %>
Why the action "/search_zip_code" isn't reached by the submit_tag button? Even if I change this route to a :post method, it doesn't work.
Thank you,
Guilherme
Upvotes: 0
Views: 1475
Reputation: 125
Hi can you try with the following code for the nested form
<%= form_for @object, url => { controller: 'controller', action: 'create', method: :get } do |f| %>
<%= f.text_field :first_name %>
<%= f.submit %>
<% end %>
Upvotes: 0
Reputation: 81
So guys, according to https://launchschool.com/blog/the-detailed-guide-on-how-ajax-works-with-ruby-on-rails and your suggestions, my solution should look like:
My main _form.html.erb:
<%= form_for(@model) do |m|%>
<%= m.label :field_1 %>
<%= m.text_field :field_1 %>
<%= m.label :field_2 %>
<%= m.text_field :field_2 %>
<div class="field">
<%= m.label :zip %>
<%= m.text_field :zip %>
<input type="button" id="search" value="Search" >
</div>
<div id="address-data" style="display:none;"></div>
<script type="text/javascript" charset="UTF-8">
$("#search").click(function() {
$.ajax({
url: '/search_zip_code?zip=' + m_zip.value,
type: 'get'
});
});
</script>
<%= m.submit %>
<% end %>
The controller action:
def search_zip_code
@add_zip = search(params[:zip]
respond_to do |format|
format.js
end
end
Then, I need a search_zip_code.js.erb file:
$('#address-data').html("<%= j (render 'form-zip') %>");
$('#address-data').slideDown(350);
The search_zip_code.html.erb, which just contains:
<%= render 'form-zip' %>
And finally, the _form-zip.html.erb partial:
<%= simple_form_for @add_zip, remote: true do |z| %>
<%= z.input :street %>
<% end %>
The good news is that the zip param is being correctly passed to search_zip_code method.
But the partial isn't being rendered: I've put breakpoints in all these erb files. The search_zip_code.js.erb is being reached, but the search_zip_code.html.erb and, of course, the _form-zip.html.erb, are not.
Am I missing something?
Thank you!
Guilherme
Upvotes: 0