jquery Rails错误:错误Controller::UnknownFormat缺少此请求格式和变量的模板

wd2eg0qa  于 5个月前  发布在  jQuery
关注(0)|答案(2)|浏览(95)

我有一个在索引页的形式,我希望该行动将由Ajax执行,在索引页显示结果.这是我在索引页的形式:

<%= 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 %>

字符串
这是我的控制器操作:

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


这是searchByDates.js.erb,在视图的文件夹中

$('#shoppingTable').html("<%= j render partial: 'shoppinglists' %>");


我已经在routes.rb文件post 'shoppings/searchByDates'中添加了路由
我错过了什么?谢谢

jdgnovmf

jdgnovmf1#

你的表单上缺少参数format

<%= form_with model: @shopping, url: { action: "searchByDates" }, format: :js, 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 %>

字符串
另外,我会将路由修改为类似post "shoppings/searchByDates", to: shoppings/search_by_dates, as: shoppings_search_by_dates的东西,这样您就可以在保持camelCase路由的同时执行snakecased操作,这样url参数就可以类似于url: shoppings_search_by_dates_path

0dxa2lsx

0dxa2lsx2#

我找到了一个解决方案,我认为问题在于它不识别remote: true选项,事实上它总是重定向到shoppings/search_by_dates URL,这就是它引发“missing template”错误的原因,它搜索了一个我没有创建的视图,因为我希望通过Ajax调用该操作。
我修改了remote:true,local:false的格式是:

<%= form_with url: shoppings_search_by_dates_path, local: false do |form| %>

字符串
这是search_by_dates操作

def search_by_dates
    @shoppings = nil
    @date_start = params[:date_start]
    @date_end = params[:date_end]
    @shoppings = Shopping.where(:date_shopping => @date_start..@date_end).order(date_shopping: :asc)
    @result_total_price = @shoppings.sum(:total_price)
    respond_to do |format|
      format.html
      format.js
    end
  end


我将js.erb文件重命名为search_by_dates.js.erb

相关问题