I have a form in index page and I want that the action will be executed by Ajax, to display the result in the Index page.
This is my form in the index Page:
<%= form_with model: @shopping, :url => {:action => "searchByDates"}, remote: true do |form| %>
<div class="form-group">
<%= form.label :date_start %>
<%= form.date_field :date_start, attribute: 'date' %>
<%= form.label :date_end %>
<%= form.date_field :date_end, attribute: 'date' %>
</div>
<div class="form-group">
<%= form.submit "Cerca", class: 'btn btn-primary' %>
</div>
<% end %>
This is my controller action:
def searchByDates
@date_start = params[:date_start]
@date_end = params[:date_end]
@shoppings = Shopping.where(:date_shopping => @date_start..@date_end)
respond_to do |format|
format.html
format.js
end
end
And this is my searchByDates.js.erb, in the folder of the view
$('#shoppingTable').html("<%= j render partial: 'shoppinglists' %>");
I have added the route in the routes.rb filepost 'shoppings/searchByDates'
What am I missing? Thanks
2
Answers
I found a solution, I think that the problem was that it did not recognize the
remote: true
option, in fact it did always a redirect to the shoppings/search_by_dates URL, and that was the reason why it raised the "missing template" error, it searched for a view that I did not create, because I wanted the action to be called via Ajax.I changed remote: true, with local: false in the form:
This is the search_by_dates action
And I renamed the js.erb file search_by_dates.js.erb
you are missing the param
format
on your form.also I would modify the route to something like
post "shoppings/searchByDates", to: shoppings/search_by_dates, as: shoppings_search_by_dates
so you have snakecased actions while keeping the camelCase route, in that way theurl
param could be something likeurl: shoppings_search_by_dates_path